##// END OF EJS Templates
Merge upstream
Fernando Perez -
r1151:8bb558e8 merge
parent child Browse files
Show More
@@ -1,359 +1,359 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 """ Implementations for various useful completers
3 """ Implementations for various useful completers
4
4
5 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
5 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
6 but the basic idea is to do:
6 but the basic idea is to do:
7
7
8 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
8 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
9
9
10 """
10 """
11 import IPython.ipapi
11 import IPython.ipapi
12 import glob,os,shlex,sys
12 import glob,os,shlex,sys
13 import inspect
13 import inspect
14 from time import time
14 from time import time
15 ip = IPython.ipapi.get()
15 ip = IPython.ipapi.get()
16
16
17 try:
17 try:
18 set
18 set
19 except:
19 except:
20 from sets import Set as set
20 from sets import Set as set
21
21
22 TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored
22 TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored
23 TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up
23 TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up
24
24
25 def quick_completer(cmd, completions):
25 def quick_completer(cmd, completions):
26 """ Easily create a trivial completer for a command.
26 """ Easily create a trivial completer for a command.
27
27
28 Takes either a list of completions, or all completions in string
28 Takes either a list of completions, or all completions in string
29 (that will be split on whitespace)
29 (that will be split on whitespace)
30
30
31 Example::
31 Example::
32
32
33 [d:\ipython]|1> import ipy_completers
33 [d:\ipython]|1> import ipy_completers
34 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
34 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
35 [d:\ipython]|3> foo b<TAB>
35 [d:\ipython]|3> foo b<TAB>
36 bar baz
36 bar baz
37 [d:\ipython]|3> foo ba
37 [d:\ipython]|3> foo ba
38 """
38 """
39 if isinstance(completions, basestring):
39 if isinstance(completions, basestring):
40
40
41 completions = completions.split()
41 completions = completions.split()
42 def do_complete(self,event):
42 def do_complete(self,event):
43 return completions
43 return completions
44
44
45 ip.set_hook('complete_command',do_complete, str_key = cmd)
45 ip.set_hook('complete_command',do_complete, str_key = cmd)
46
46
47 def getRootModules():
47 def getRootModules():
48 """
48 """
49 Returns a list containing the names of all the modules available in the
49 Returns a list containing the names of all the modules available in the
50 folders of the pythonpath.
50 folders of the pythonpath.
51 """
51 """
52 modules = []
52 modules = []
53 if ip.db.has_key('rootmodules'):
53 if ip.db.has_key('rootmodules'):
54 return ip.db['rootmodules']
54 return ip.db['rootmodules']
55 t = time()
55 t = time()
56 store = False
56 store = False
57 for path in sys.path:
57 for path in sys.path:
58 modules += moduleList(path)
58 modules += moduleList(path)
59 if time() - t >= TIMEOUT_STORAGE and not store:
59 if time() - t >= TIMEOUT_STORAGE and not store:
60 store = True
60 store = True
61 print "\nCaching the list of root modules, please wait!"
61 print "\nCaching the list of root modules, please wait!"
62 print "(This will only be done once - type '%rehashx' to " + \
62 print "(This will only be done once - type '%rehashx' to " + \
63 "reset cache!)"
63 "reset cache!)"
64 print
64 print
65 if time() - t > TIMEOUT_GIVEUP:
65 if time() - t > TIMEOUT_GIVEUP:
66 print "This is taking too long, we give up."
66 print "This is taking too long, we give up."
67 print
67 print
68 ip.db['rootmodules'] = []
68 ip.db['rootmodules'] = []
69 return []
69 return []
70
70
71 modules += sys.builtin_module_names
71 modules += sys.builtin_module_names
72
72
73 modules = list(set(modules))
73 modules = list(set(modules))
74 if '__init__' in modules:
74 if '__init__' in modules:
75 modules.remove('__init__')
75 modules.remove('__init__')
76 modules = list(set(modules))
76 modules = list(set(modules))
77 if store:
77 if store:
78 ip.db['rootmodules'] = modules
78 ip.db['rootmodules'] = modules
79 return modules
79 return modules
80
80
81 def moduleList(path):
81 def moduleList(path):
82 """
82 """
83 Return the list containing the names of the modules available in the given
83 Return the list containing the names of the modules available in the given
84 folder.
84 folder.
85 """
85 """
86
86
87 if os.path.isdir(path):
87 if os.path.isdir(path):
88 folder_list = os.listdir(path)
88 folder_list = os.listdir(path)
89 else:
89 else:
90 folder_list = []
90 folder_list = []
91 #folder_list = glob.glob(os.path.join(path,'*'))
91 #folder_list = glob.glob(os.path.join(path,'*'))
92 folder_list = [p for p in folder_list \
92 folder_list = [p for p in folder_list \
93 if os.path.exists(os.path.join(path, p,'__init__.py'))\
93 if os.path.exists(os.path.join(path, p,'__init__.py'))\
94 or p[-3:] in ('.py','.so')\
94 or p[-3:] in ('.py','.so')\
95 or p[-4:] in ('.pyc','.pyo')]
95 or p[-4:] in ('.pyc','.pyo','.pyd')]
96
96
97 folder_list = [os.path.basename(p).split('.')[0] for p in folder_list]
97 folder_list = [os.path.basename(p).split('.')[0] for p in folder_list]
98 return folder_list
98 return folder_list
99
99
100 def moduleCompletion(line):
100 def moduleCompletion(line):
101 """
101 """
102 Returns a list containing the completion possibilities for an import line.
102 Returns a list containing the completion possibilities for an import line.
103 The line looks like this :
103 The line looks like this :
104 'import xml.d'
104 'import xml.d'
105 'from xml.dom import'
105 'from xml.dom import'
106 """
106 """
107 def tryImport(mod, only_modules=False):
107 def tryImport(mod, only_modules=False):
108 def isImportable(module, attr):
108 def isImportable(module, attr):
109 if only_modules:
109 if only_modules:
110 return inspect.ismodule(getattr(module, attr))
110 return inspect.ismodule(getattr(module, attr))
111 else:
111 else:
112 return not(attr[:2] == '__' and attr[-2:] == '__')
112 return not(attr[:2] == '__' and attr[-2:] == '__')
113 try:
113 try:
114 m = __import__(mod)
114 m = __import__(mod)
115 except:
115 except:
116 return []
116 return []
117 mods = mod.split('.')
117 mods = mod.split('.')
118 for module in mods[1:]:
118 for module in mods[1:]:
119 m = getattr(m,module)
119 m = getattr(m,module)
120 if (not hasattr(m, '__file__')) or (not only_modules) or\
120 if (not hasattr(m, '__file__')) or (not only_modules) or\
121 (hasattr(m, '__file__') and '__init__' in m.__file__):
121 (hasattr(m, '__file__') and '__init__' in m.__file__):
122 completion_list = [attr for attr in dir(m) if isImportable(m, attr)]
122 completion_list = [attr for attr in dir(m) if isImportable(m, attr)]
123 completion_list.extend(getattr(m,'__all__',[]))
123 completion_list.extend(getattr(m,'__all__',[]))
124 if hasattr(m, '__file__') and '__init__' in m.__file__:
124 if hasattr(m, '__file__') and '__init__' in m.__file__:
125 completion_list.extend(moduleList(os.path.dirname(m.__file__)))
125 completion_list.extend(moduleList(os.path.dirname(m.__file__)))
126 completion_list = list(set(completion_list))
126 completion_list = list(set(completion_list))
127 if '__init__' in completion_list:
127 if '__init__' in completion_list:
128 completion_list.remove('__init__')
128 completion_list.remove('__init__')
129 return completion_list
129 return completion_list
130
130
131 words = line.split(' ')
131 words = line.split(' ')
132 if len(words) == 3 and words[0] == 'from':
132 if len(words) == 3 and words[0] == 'from':
133 return ['import ']
133 return ['import ']
134 if len(words) < 3 and (words[0] in ['import','from']) :
134 if len(words) < 3 and (words[0] in ['import','from']) :
135 if len(words) == 1:
135 if len(words) == 1:
136 return getRootModules()
136 return getRootModules()
137 mod = words[1].split('.')
137 mod = words[1].split('.')
138 if len(mod) < 2:
138 if len(mod) < 2:
139 return getRootModules()
139 return getRootModules()
140 completion_list = tryImport('.'.join(mod[:-1]), True)
140 completion_list = tryImport('.'.join(mod[:-1]), True)
141 completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list]
141 completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list]
142 return completion_list
142 return completion_list
143 if len(words) >= 3 and words[0] == 'from':
143 if len(words) >= 3 and words[0] == 'from':
144 mod = words[1]
144 mod = words[1]
145 return tryImport(mod)
145 return tryImport(mod)
146
146
147 def vcs_completer(commands, event):
147 def vcs_completer(commands, event):
148 """ utility to make writing typical version control app completers easier
148 """ utility to make writing typical version control app completers easier
149
149
150 VCS command line apps typically have the format:
150 VCS command line apps typically have the format:
151
151
152 [sudo ]PROGNAME [help] [command] file file...
152 [sudo ]PROGNAME [help] [command] file file...
153
153
154 """
154 """
155
155
156
156
157 cmd_param = event.line.split()
157 cmd_param = event.line.split()
158 if event.line.endswith(' '):
158 if event.line.endswith(' '):
159 cmd_param.append('')
159 cmd_param.append('')
160
160
161 if cmd_param[0] == 'sudo':
161 if cmd_param[0] == 'sudo':
162 cmd_param = cmd_param[1:]
162 cmd_param = cmd_param[1:]
163
163
164 if len(cmd_param) == 2 or 'help' in cmd_param:
164 if len(cmd_param) == 2 or 'help' in cmd_param:
165 return commands.split()
165 return commands.split()
166
166
167 return ip.IP.Completer.file_matches(event.symbol)
167 return ip.IP.Completer.file_matches(event.symbol)
168
168
169
169
170 pkg_cache = None
170 pkg_cache = None
171
171
172 def module_completer(self,event):
172 def module_completer(self,event):
173 """ Give completions after user has typed 'import ...' or 'from ...'"""
173 """ Give completions after user has typed 'import ...' or 'from ...'"""
174
174
175 # This works in all versions of python. While 2.5 has
175 # This works in all versions of python. While 2.5 has
176 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
176 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
177 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
177 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
178 # of possibly problematic side effects.
178 # of possibly problematic side effects.
179 # This search the folders in the sys.path for available modules.
179 # This search the folders in the sys.path for available modules.
180
180
181 return moduleCompletion(event.line)
181 return moduleCompletion(event.line)
182
182
183
183
184 svn_commands = """\
184 svn_commands = """\
185 add blame praise annotate ann cat checkout co cleanup commit ci copy
185 add blame praise annotate ann cat checkout co cleanup commit ci copy
186 cp delete del remove rm diff di export help ? h import info list ls
186 cp delete del remove rm diff di export help ? h import info list ls
187 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
187 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
188 pe propget pget pg proplist plist pl propset pset ps resolved revert
188 pe propget pget pg proplist plist pl propset pset ps resolved revert
189 status stat st switch sw unlock update
189 status stat st switch sw unlock update
190 """
190 """
191
191
192 def svn_completer(self,event):
192 def svn_completer(self,event):
193 return vcs_completer(svn_commands, event)
193 return vcs_completer(svn_commands, event)
194
194
195
195
196 hg_commands = """
196 hg_commands = """
197 add addremove annotate archive backout branch branches bundle cat
197 add addremove annotate archive backout branch branches bundle cat
198 clone commit copy diff export grep heads help identify import incoming
198 clone commit copy diff export grep heads help identify import incoming
199 init locate log manifest merge outgoing parents paths pull push
199 init locate log manifest merge outgoing parents paths pull push
200 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
200 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
201 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
201 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
202 qselect qseries qtop qunapplied recover remove rename revert rollback
202 qselect qseries qtop qunapplied recover remove rename revert rollback
203 root serve showconfig status strip tag tags tip unbundle update verify
203 root serve showconfig status strip tag tags tip unbundle update verify
204 version
204 version
205 """
205 """
206
206
207 def hg_completer(self,event):
207 def hg_completer(self,event):
208 """ Completer for mercurial commands """
208 """ Completer for mercurial commands """
209
209
210 return vcs_completer(hg_commands, event)
210 return vcs_completer(hg_commands, event)
211
211
212
212
213
213
214 __bzr_commands = None
214 __bzr_commands = None
215
215
216 def bzr_commands():
216 def bzr_commands():
217 global __bzr_commands
217 global __bzr_commands
218 if __bzr_commands is not None:
218 if __bzr_commands is not None:
219 return __bzr_commands
219 return __bzr_commands
220 out = os.popen('bzr help commands')
220 out = os.popen('bzr help commands')
221 __bzr_commands = [l.split()[0] for l in out]
221 __bzr_commands = [l.split()[0] for l in out]
222 return __bzr_commands
222 return __bzr_commands
223
223
224 def bzr_completer(self,event):
224 def bzr_completer(self,event):
225 """ Completer for bazaar commands """
225 """ Completer for bazaar commands """
226 cmd_param = event.line.split()
226 cmd_param = event.line.split()
227 if event.line.endswith(' '):
227 if event.line.endswith(' '):
228 cmd_param.append('')
228 cmd_param.append('')
229
229
230 if len(cmd_param) > 2:
230 if len(cmd_param) > 2:
231 cmd = cmd_param[1]
231 cmd = cmd_param[1]
232 param = cmd_param[-1]
232 param = cmd_param[-1]
233 output_file = (param == '--output=')
233 output_file = (param == '--output=')
234 if cmd == 'help':
234 if cmd == 'help':
235 return bzr_commands()
235 return bzr_commands()
236 elif cmd in ['bundle-revisions','conflicts',
236 elif cmd in ['bundle-revisions','conflicts',
237 'deleted','nick','register-branch',
237 'deleted','nick','register-branch',
238 'serve','unbind','upgrade','version',
238 'serve','unbind','upgrade','version',
239 'whoami'] and not output_file:
239 'whoami'] and not output_file:
240 return []
240 return []
241 else:
241 else:
242 # the rest are probably file names
242 # the rest are probably file names
243 return ip.IP.Completer.file_matches(event.symbol)
243 return ip.IP.Completer.file_matches(event.symbol)
244
244
245 return bzr_commands()
245 return bzr_commands()
246
246
247
247
248 def shlex_split(x):
248 def shlex_split(x):
249 """Helper function to split lines into segments."""
249 """Helper function to split lines into segments."""
250 #shlex.split raise exception if syntax error in sh syntax
250 #shlex.split raise exception if syntax error in sh syntax
251 #for example if no closing " is found. This function keeps dropping
251 #for example if no closing " is found. This function keeps dropping
252 #the last character of the line until shlex.split does not raise
252 #the last character of the line until shlex.split does not raise
253 #exception. Adds end of the line to the result of shlex.split
253 #exception. Adds end of the line to the result of shlex.split
254 #example: %run "c:/python -> ['%run','"c:/python']
254 #example: %run "c:/python -> ['%run','"c:/python']
255 endofline=[]
255 endofline=[]
256 while x!="":
256 while x!="":
257 try:
257 try:
258 comps=shlex.split(x)
258 comps=shlex.split(x)
259 if len(endofline)>=1:
259 if len(endofline)>=1:
260 comps.append("".join(endofline))
260 comps.append("".join(endofline))
261 return comps
261 return comps
262 except ValueError:
262 except ValueError:
263 endofline=[x[-1:]]+endofline
263 endofline=[x[-1:]]+endofline
264 x=x[:-1]
264 x=x[:-1]
265 return ["".join(endofline)]
265 return ["".join(endofline)]
266
266
267 def runlistpy(self, event):
267 def runlistpy(self, event):
268 comps = shlex_split(event.line)
268 comps = shlex_split(event.line)
269 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
269 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
270
270
271 #print "\nev=",event # dbg
271 #print "\nev=",event # dbg
272 #print "rp=",relpath # dbg
272 #print "rp=",relpath # dbg
273 #print 'comps=',comps # dbg
273 #print 'comps=',comps # dbg
274
274
275 lglob = glob.glob
275 lglob = glob.glob
276 isdir = os.path.isdir
276 isdir = os.path.isdir
277 if relpath.startswith('~'):
277 if relpath.startswith('~'):
278 relpath = os.path.expanduser(relpath)
278 relpath = os.path.expanduser(relpath)
279 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
279 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
280 if isdir(f)]
280 if isdir(f)]
281
281
282 # Find if the user has already typed the first filename, after which we
282 # Find if the user has already typed the first filename, after which we
283 # should complete on all files, since after the first one other files may
283 # should complete on all files, since after the first one other files may
284 # be arguments to the input script.
284 # be arguments to the input script.
285 #filter(
285 #filter(
286 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or
286 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or
287 f.endswith('.pyw'),comps):
287 f.endswith('.pyw'),comps):
288 pys = [f.replace('\\','/') for f in lglob('*')]
288 pys = [f.replace('\\','/') for f in lglob('*')]
289 else:
289 else:
290 pys = [f.replace('\\','/')
290 pys = [f.replace('\\','/')
291 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
291 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
292 lglob(relpath + '*.pyw')]
292 lglob(relpath + '*.pyw')]
293 return dirs + pys
293 return dirs + pys
294
294
295
295
296 def cd_completer(self, event):
296 def cd_completer(self, event):
297 relpath = event.symbol
297 relpath = event.symbol
298 #print event # dbg
298 #print event # dbg
299 if '-b' in event.line:
299 if '-b' in event.line:
300 # return only bookmark completions
300 # return only bookmark completions
301 bkms = self.db.get('bookmarks',{})
301 bkms = self.db.get('bookmarks',{})
302 return bkms.keys()
302 return bkms.keys()
303
303
304
304
305 if event.symbol == '-':
305 if event.symbol == '-':
306 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
306 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
307 # jump in directory history by number
307 # jump in directory history by number
308 fmt = '-%0' + width_dh +'d [%s]'
308 fmt = '-%0' + width_dh +'d [%s]'
309 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
309 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
310 if len(ents) > 1:
310 if len(ents) > 1:
311 return ents
311 return ents
312 return []
312 return []
313
313
314 if relpath.startswith('~'):
314 if relpath.startswith('~'):
315 relpath = os.path.expanduser(relpath).replace('\\','/')
315 relpath = os.path.expanduser(relpath).replace('\\','/')
316 found = []
316 found = []
317 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
317 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
318 if os.path.isdir(f)]:
318 if os.path.isdir(f)]:
319 if ' ' in d:
319 if ' ' in d:
320 # we don't want to deal with any of that, complex code
320 # we don't want to deal with any of that, complex code
321 # for this is elsewhere
321 # for this is elsewhere
322 raise IPython.ipapi.TryNext
322 raise IPython.ipapi.TryNext
323 found.append( d )
323 found.append( d )
324
324
325 if not found:
325 if not found:
326 if os.path.isdir(relpath):
326 if os.path.isdir(relpath):
327 return [relpath]
327 return [relpath]
328 raise IPython.ipapi.TryNext
328 raise IPython.ipapi.TryNext
329 return found
329 return found
330
330
331 def apt_get_packages(prefix):
331 def apt_get_packages(prefix):
332 out = os.popen('apt-cache pkgnames')
332 out = os.popen('apt-cache pkgnames')
333 for p in out:
333 for p in out:
334 if p.startswith(prefix):
334 if p.startswith(prefix):
335 yield p.rstrip()
335 yield p.rstrip()
336
336
337
337
338 apt_commands = """\
338 apt_commands = """\
339 update upgrade install remove purge source build-dep dist-upgrade
339 update upgrade install remove purge source build-dep dist-upgrade
340 dselect-upgrade clean autoclean check"""
340 dselect-upgrade clean autoclean check"""
341
341
342 def apt_completer(self, event):
342 def apt_completer(self, event):
343 """ Completer for apt-get (uses apt-cache internally)
343 """ Completer for apt-get (uses apt-cache internally)
344
344
345 """
345 """
346
346
347
347
348 cmd_param = event.line.split()
348 cmd_param = event.line.split()
349 if event.line.endswith(' '):
349 if event.line.endswith(' '):
350 cmd_param.append('')
350 cmd_param.append('')
351
351
352 if cmd_param[0] == 'sudo':
352 if cmd_param[0] == 'sudo':
353 cmd_param = cmd_param[1:]
353 cmd_param = cmd_param[1:]
354
354
355 if len(cmd_param) == 2 or 'help' in cmd_param:
355 if len(cmd_param) == 2 or 'help' in cmd_param:
356 return apt_commands.split()
356 return apt_commands.split()
357
357
358 return list(apt_get_packages(event.symbol))
358 return list(apt_get_packages(event.symbol))
359
359
@@ -1,3296 +1,3311 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 #***************************************************************************
64 #***************************************************************************
65 # Utility functions
65 # Utility functions
66 def on_off(tag):
66 def on_off(tag):
67 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
67 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
68 return ['OFF','ON'][tag]
68 return ['OFF','ON'][tag]
69
69
70 class Bunch: pass
70 class Bunch: pass
71
71
72 def compress_dhist(dh):
72 def compress_dhist(dh):
73 head, tail = dh[:-10], dh[-10:]
73 head, tail = dh[:-10], dh[-10:]
74
74
75 newhead = []
75 newhead = []
76 done = Set()
76 done = Set()
77 for h in head:
77 for h in head:
78 if h in done:
78 if h in done:
79 continue
79 continue
80 newhead.append(h)
80 newhead.append(h)
81 done.add(h)
81 done.add(h)
82
82
83 return newhead + tail
83 return newhead + tail
84
84
85
85
86 #***************************************************************************
86 #***************************************************************************
87 # Main class implementing Magic functionality
87 # Main class implementing Magic functionality
88 class Magic:
88 class Magic:
89 """Magic functions for InteractiveShell.
89 """Magic functions for InteractiveShell.
90
90
91 Shell functions which can be reached as %function_name. All magic
91 Shell functions which can be reached as %function_name. All magic
92 functions should accept a string, which they can parse for their own
92 functions should accept a string, which they can parse for their own
93 needs. This can make some functions easier to type, eg `%cd ../`
93 needs. This can make some functions easier to type, eg `%cd ../`
94 vs. `%cd("../")`
94 vs. `%cd("../")`
95
95
96 ALL definitions MUST begin with the prefix magic_. The user won't need it
96 ALL definitions MUST begin with the prefix magic_. The user won't need it
97 at the command line, but it is is needed in the definition. """
97 at the command line, but it is is needed in the definition. """
98
98
99 # class globals
99 # class globals
100 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
100 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
101 'Automagic is ON, % prefix NOT needed for magic functions.']
101 'Automagic is ON, % prefix NOT needed for magic functions.']
102
102
103 #......................................................................
103 #......................................................................
104 # some utility functions
104 # some utility functions
105
105
106 def __init__(self,shell):
106 def __init__(self,shell):
107
107
108 self.options_table = {}
108 self.options_table = {}
109 if profile is None:
109 if profile is None:
110 self.magic_prun = self.profile_missing_notice
110 self.magic_prun = self.profile_missing_notice
111 self.shell = shell
111 self.shell = shell
112
112
113 # namespace for holding state we may need
113 # namespace for holding state we may need
114 self._magic_state = Bunch()
114 self._magic_state = Bunch()
115
115
116 def profile_missing_notice(self, *args, **kwargs):
116 def profile_missing_notice(self, *args, **kwargs):
117 error("""\
117 error("""\
118 The profile module could not be found. If you are a Debian user,
118 The profile module could not be found. If you are a Debian user,
119 it has been removed from the standard Debian package because of its non-free
119 it has been removed from the standard Debian package because of its non-free
120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
121
121
122 def default_option(self,fn,optstr):
122 def default_option(self,fn,optstr):
123 """Make an entry in the options_table for fn, with value optstr"""
123 """Make an entry in the options_table for fn, with value optstr"""
124
124
125 if fn not in self.lsmagic():
125 if fn not in self.lsmagic():
126 error("%s is not a magic function" % fn)
126 error("%s is not a magic function" % fn)
127 self.options_table[fn] = optstr
127 self.options_table[fn] = optstr
128
128
129 def lsmagic(self):
129 def lsmagic(self):
130 """Return a list of currently available magic functions.
130 """Return a list of currently available magic functions.
131
131
132 Gives a list of the bare names after mangling (['ls','cd', ...], not
132 Gives a list of the bare names after mangling (['ls','cd', ...], not
133 ['magic_ls','magic_cd',...]"""
133 ['magic_ls','magic_cd',...]"""
134
134
135 # FIXME. This needs a cleanup, in the way the magics list is built.
135 # FIXME. This needs a cleanup, in the way the magics list is built.
136
136
137 # magics in class definition
137 # magics in class definition
138 class_magic = lambda fn: fn.startswith('magic_') and \
138 class_magic = lambda fn: fn.startswith('magic_') and \
139 callable(Magic.__dict__[fn])
139 callable(Magic.__dict__[fn])
140 # in instance namespace (run-time user additions)
140 # in instance namespace (run-time user additions)
141 inst_magic = lambda fn: fn.startswith('magic_') and \
141 inst_magic = lambda fn: fn.startswith('magic_') and \
142 callable(self.__dict__[fn])
142 callable(self.__dict__[fn])
143 # and bound magics by user (so they can access self):
143 # and bound magics by user (so they can access self):
144 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
144 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
145 callable(self.__class__.__dict__[fn])
145 callable(self.__class__.__dict__[fn])
146 magics = filter(class_magic,Magic.__dict__.keys()) + \
146 magics = filter(class_magic,Magic.__dict__.keys()) + \
147 filter(inst_magic,self.__dict__.keys()) + \
147 filter(inst_magic,self.__dict__.keys()) + \
148 filter(inst_bound_magic,self.__class__.__dict__.keys())
148 filter(inst_bound_magic,self.__class__.__dict__.keys())
149 out = []
149 out = []
150 for fn in magics:
150 for fn in Set(magics):
151 out.append(fn.replace('magic_','',1))
151 out.append(fn.replace('magic_','',1))
152 out.sort()
152 out.sort()
153 return out
153 return out
154
154
155 def extract_input_slices(self,slices,raw=False):
155 def extract_input_slices(self,slices,raw=False):
156 """Return as a string a set of input history slices.
156 """Return as a string a set of input history slices.
157
157
158 Inputs:
158 Inputs:
159
159
160 - slices: the set of slices is given as a list of strings (like
160 - slices: the set of slices is given as a list of strings (like
161 ['1','4:8','9'], since this function is for use by magic functions
161 ['1','4:8','9'], since this function is for use by magic functions
162 which get their arguments as strings.
162 which get their arguments as strings.
163
163
164 Optional inputs:
164 Optional inputs:
165
165
166 - raw(False): by default, the processed input is used. If this is
166 - raw(False): by default, the processed input is used. If this is
167 true, the raw input history is used instead.
167 true, the raw input history is used instead.
168
168
169 Note that slices can be called with two notations:
169 Note that slices can be called with two notations:
170
170
171 N:M -> standard python form, means including items N...(M-1).
171 N:M -> standard python form, means including items N...(M-1).
172
172
173 N-M -> include items N..M (closed endpoint)."""
173 N-M -> include items N..M (closed endpoint)."""
174
174
175 if raw:
175 if raw:
176 hist = self.shell.input_hist_raw
176 hist = self.shell.input_hist_raw
177 else:
177 else:
178 hist = self.shell.input_hist
178 hist = self.shell.input_hist
179
179
180 cmds = []
180 cmds = []
181 for chunk in slices:
181 for chunk in slices:
182 if ':' in chunk:
182 if ':' in chunk:
183 ini,fin = map(int,chunk.split(':'))
183 ini,fin = map(int,chunk.split(':'))
184 elif '-' in chunk:
184 elif '-' in chunk:
185 ini,fin = map(int,chunk.split('-'))
185 ini,fin = map(int,chunk.split('-'))
186 fin += 1
186 fin += 1
187 else:
187 else:
188 ini = int(chunk)
188 ini = int(chunk)
189 fin = ini+1
189 fin = ini+1
190 cmds.append(hist[ini:fin])
190 cmds.append(hist[ini:fin])
191 return cmds
191 return cmds
192
192
193 def _ofind(self, oname, namespaces=None):
193 def _ofind(self, oname, namespaces=None):
194 """Find an object in the available namespaces.
194 """Find an object in the available namespaces.
195
195
196 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
197
197
198 Has special code to detect magic functions.
198 Has special code to detect magic functions.
199 """
199 """
200
200
201 oname = oname.strip()
201 oname = oname.strip()
202
202
203 alias_ns = None
203 alias_ns = None
204 if namespaces is None:
204 if namespaces is None:
205 # Namespaces to search in:
205 # Namespaces to search in:
206 # Put them in a list. The order is important so that we
206 # Put them in a list. The order is important so that we
207 # find things in the same order that Python finds them.
207 # find things in the same order that Python finds them.
208 namespaces = [ ('Interactive', self.shell.user_ns),
208 namespaces = [ ('Interactive', self.shell.user_ns),
209 ('IPython internal', self.shell.internal_ns),
209 ('IPython internal', self.shell.internal_ns),
210 ('Python builtin', __builtin__.__dict__),
210 ('Python builtin', __builtin__.__dict__),
211 ('Alias', self.shell.alias_table),
211 ('Alias', self.shell.alias_table),
212 ]
212 ]
213 alias_ns = self.shell.alias_table
213 alias_ns = self.shell.alias_table
214
214
215 # initialize results to 'null'
215 # initialize results to 'null'
216 found = 0; obj = None; ospace = None; ds = None;
216 found = 0; obj = None; ospace = None; ds = None;
217 ismagic = 0; isalias = 0; parent = None
217 ismagic = 0; isalias = 0; parent = None
218
218
219 # Look for the given name by splitting it in parts. If the head is
219 # Look for the given name by splitting it in parts. If the head is
220 # found, then we look for all the remaining parts as members, and only
220 # found, then we look for all the remaining parts as members, and only
221 # declare success if we can find them all.
221 # declare success if we can find them all.
222 oname_parts = oname.split('.')
222 oname_parts = oname.split('.')
223 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
223 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
224 for nsname,ns in namespaces:
224 for nsname,ns in namespaces:
225 try:
225 try:
226 obj = ns[oname_head]
226 obj = ns[oname_head]
227 except KeyError:
227 except KeyError:
228 continue
228 continue
229 else:
229 else:
230 #print 'oname_rest:', oname_rest # dbg
230 #print 'oname_rest:', oname_rest # dbg
231 for part in oname_rest:
231 for part in oname_rest:
232 try:
232 try:
233 parent = obj
233 parent = obj
234 obj = getattr(obj,part)
234 obj = getattr(obj,part)
235 except:
235 except:
236 # Blanket except b/c some badly implemented objects
236 # Blanket except b/c some badly implemented objects
237 # allow __getattr__ to raise exceptions other than
237 # allow __getattr__ to raise exceptions other than
238 # AttributeError, which then crashes IPython.
238 # AttributeError, which then crashes IPython.
239 break
239 break
240 else:
240 else:
241 # If we finish the for loop (no break), we got all members
241 # If we finish the for loop (no break), we got all members
242 found = 1
242 found = 1
243 ospace = nsname
243 ospace = nsname
244 if ns == alias_ns:
244 if ns == alias_ns:
245 isalias = 1
245 isalias = 1
246 break # namespace loop
246 break # namespace loop
247
247
248 # Try to see if it's magic
248 # Try to see if it's magic
249 if not found:
249 if not found:
250 if oname.startswith(self.shell.ESC_MAGIC):
250 if oname.startswith(self.shell.ESC_MAGIC):
251 oname = oname[1:]
251 oname = oname[1:]
252 obj = getattr(self,'magic_'+oname,None)
252 obj = getattr(self,'magic_'+oname,None)
253 if obj is not None:
253 if obj is not None:
254 found = 1
254 found = 1
255 ospace = 'IPython internal'
255 ospace = 'IPython internal'
256 ismagic = 1
256 ismagic = 1
257
257
258 # Last try: special-case some literals like '', [], {}, etc:
258 # Last try: special-case some literals like '', [], {}, etc:
259 if not found and oname_head in ["''",'""','[]','{}','()']:
259 if not found and oname_head in ["''",'""','[]','{}','()']:
260 obj = eval(oname_head)
260 obj = eval(oname_head)
261 found = 1
261 found = 1
262 ospace = 'Interactive'
262 ospace = 'Interactive'
263
263
264 return {'found':found, 'obj':obj, 'namespace':ospace,
264 return {'found':found, 'obj':obj, 'namespace':ospace,
265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
266
266
267 def arg_err(self,func):
267 def arg_err(self,func):
268 """Print docstring if incorrect arguments were passed"""
268 """Print docstring if incorrect arguments were passed"""
269 print 'Error in arguments:'
269 print 'Error in arguments:'
270 print OInspect.getdoc(func)
270 print OInspect.getdoc(func)
271
271
272 def format_latex(self,strng):
272 def format_latex(self,strng):
273 """Format a string for latex inclusion."""
273 """Format a string for latex inclusion."""
274
274
275 # Characters that need to be escaped for latex:
275 # Characters that need to be escaped for latex:
276 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
276 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
277 # Magic command names as headers:
277 # Magic command names as headers:
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 re.MULTILINE)
279 re.MULTILINE)
280 # Magic commands
280 # Magic commands
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 re.MULTILINE)
282 re.MULTILINE)
283 # Paragraph continue
283 # Paragraph continue
284 par_re = re.compile(r'\\$',re.MULTILINE)
284 par_re = re.compile(r'\\$',re.MULTILINE)
285
285
286 # The "\n" symbol
286 # The "\n" symbol
287 newline_re = re.compile(r'\\n')
287 newline_re = re.compile(r'\\n')
288
288
289 # Now build the string for output:
289 # Now build the string for output:
290 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
290 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
291 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
291 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
292 strng)
292 strng)
293 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
293 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
294 strng = par_re.sub(r'\\\\',strng)
294 strng = par_re.sub(r'\\\\',strng)
295 strng = escape_re.sub(r'\\\1',strng)
295 strng = escape_re.sub(r'\\\1',strng)
296 strng = newline_re.sub(r'\\textbackslash{}n',strng)
296 strng = newline_re.sub(r'\\textbackslash{}n',strng)
297 return strng
297 return strng
298
298
299 def format_screen(self,strng):
299 def format_screen(self,strng):
300 """Format a string for screen printing.
300 """Format a string for screen printing.
301
301
302 This removes some latex-type format codes."""
302 This removes some latex-type format codes."""
303 # Paragraph continue
303 # Paragraph continue
304 par_re = re.compile(r'\\$',re.MULTILINE)
304 par_re = re.compile(r'\\$',re.MULTILINE)
305 strng = par_re.sub('',strng)
305 strng = par_re.sub('',strng)
306 return strng
306 return strng
307
307
308 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
308 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
309 """Parse options passed to an argument string.
309 """Parse options passed to an argument string.
310
310
311 The interface is similar to that of getopt(), but it returns back a
311 The interface is similar to that of getopt(), but it returns back a
312 Struct with the options as keys and the stripped argument string still
312 Struct with the options as keys and the stripped argument string still
313 as a string.
313 as a string.
314
314
315 arg_str is quoted as a true sys.argv vector by using shlex.split.
315 arg_str is quoted as a true sys.argv vector by using shlex.split.
316 This allows us to easily expand variables, glob files, quote
316 This allows us to easily expand variables, glob files, quote
317 arguments, etc.
317 arguments, etc.
318
318
319 Options:
319 Options:
320 -mode: default 'string'. If given as 'list', the argument string is
320 -mode: default 'string'. If given as 'list', the argument string is
321 returned as a list (split on whitespace) instead of a string.
321 returned as a list (split on whitespace) instead of a string.
322
322
323 -list_all: put all option values in lists. Normally only options
323 -list_all: put all option values in lists. Normally only options
324 appearing more than once are put in a list.
324 appearing more than once are put in a list.
325
325
326 -posix (True): whether to split the input line in POSIX mode or not,
326 -posix (True): whether to split the input line in POSIX mode or not,
327 as per the conventions outlined in the shlex module from the
327 as per the conventions outlined in the shlex module from the
328 standard library."""
328 standard library."""
329
329
330 # inject default options at the beginning of the input line
330 # inject default options at the beginning of the input line
331 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
331 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
332 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
332 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
333
333
334 mode = kw.get('mode','string')
334 mode = kw.get('mode','string')
335 if mode not in ['string','list']:
335 if mode not in ['string','list']:
336 raise ValueError,'incorrect mode given: %s' % mode
336 raise ValueError,'incorrect mode given: %s' % mode
337 # Get options
337 # Get options
338 list_all = kw.get('list_all',0)
338 list_all = kw.get('list_all',0)
339 posix = kw.get('posix',True)
339 posix = kw.get('posix',True)
340
340
341 # Check if we have more than one argument to warrant extra processing:
341 # Check if we have more than one argument to warrant extra processing:
342 odict = {} # Dictionary with options
342 odict = {} # Dictionary with options
343 args = arg_str.split()
343 args = arg_str.split()
344 if len(args) >= 1:
344 if len(args) >= 1:
345 # If the list of inputs only has 0 or 1 thing in it, there's no
345 # If the list of inputs only has 0 or 1 thing in it, there's no
346 # need to look for options
346 # need to look for options
347 argv = arg_split(arg_str,posix)
347 argv = arg_split(arg_str,posix)
348 # Do regular option processing
348 # Do regular option processing
349 try:
349 try:
350 opts,args = getopt(argv,opt_str,*long_opts)
350 opts,args = getopt(argv,opt_str,*long_opts)
351 except GetoptError,e:
351 except GetoptError,e:
352 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
352 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
353 " ".join(long_opts)))
353 " ".join(long_opts)))
354 for o,a in opts:
354 for o,a in opts:
355 if o.startswith('--'):
355 if o.startswith('--'):
356 o = o[2:]
356 o = o[2:]
357 else:
357 else:
358 o = o[1:]
358 o = o[1:]
359 try:
359 try:
360 odict[o].append(a)
360 odict[o].append(a)
361 except AttributeError:
361 except AttributeError:
362 odict[o] = [odict[o],a]
362 odict[o] = [odict[o],a]
363 except KeyError:
363 except KeyError:
364 if list_all:
364 if list_all:
365 odict[o] = [a]
365 odict[o] = [a]
366 else:
366 else:
367 odict[o] = a
367 odict[o] = a
368
368
369 # Prepare opts,args for return
369 # Prepare opts,args for return
370 opts = Struct(odict)
370 opts = Struct(odict)
371 if mode == 'string':
371 if mode == 'string':
372 args = ' '.join(args)
372 args = ' '.join(args)
373
373
374 return opts,args
374 return opts,args
375
375
376 #......................................................................
376 #......................................................................
377 # And now the actual magic functions
377 # And now the actual magic functions
378
378
379 # Functions for IPython shell work (vars,funcs, config, etc)
379 # Functions for IPython shell work (vars,funcs, config, etc)
380 def magic_lsmagic(self, parameter_s = ''):
380 def magic_lsmagic(self, parameter_s = ''):
381 """List currently available magic functions."""
381 """List currently available magic functions."""
382 mesc = self.shell.ESC_MAGIC
382 mesc = self.shell.ESC_MAGIC
383 print 'Available magic functions:\n'+mesc+\
383 print 'Available magic functions:\n'+mesc+\
384 (' '+mesc).join(self.lsmagic())
384 (' '+mesc).join(self.lsmagic())
385 print '\n' + Magic.auto_status[self.shell.rc.automagic]
385 print '\n' + Magic.auto_status[self.shell.rc.automagic]
386 return None
386 return None
387
387
388 def magic_magic(self, parameter_s = ''):
388 def magic_magic(self, parameter_s = ''):
389 """Print information about the magic function system."""
389 """Print information about the magic function system.
390
391 Supported formats: -latex, -brief, -rest
392 """
390
393
391 mode = ''
394 mode = ''
392 try:
395 try:
393 if parameter_s.split()[0] == '-latex':
396 if parameter_s.split()[0] == '-latex':
394 mode = 'latex'
397 mode = 'latex'
395 if parameter_s.split()[0] == '-brief':
398 if parameter_s.split()[0] == '-brief':
396 mode = 'brief'
399 mode = 'brief'
400 if parameter_s.split()[0] == '-rest':
401 mode = 'rest'
402 rest_docs = []
397 except:
403 except:
398 pass
404 pass
399
405
400 magic_docs = []
406 magic_docs = []
401 for fname in self.lsmagic():
407 for fname in self.lsmagic():
402 mname = 'magic_' + fname
408 mname = 'magic_' + fname
403 for space in (Magic,self,self.__class__):
409 for space in (Magic,self,self.__class__):
404 try:
410 try:
405 fn = space.__dict__[mname]
411 fn = space.__dict__[mname]
406 except KeyError:
412 except KeyError:
407 pass
413 pass
408 else:
414 else:
409 break
415 break
410 if mode == 'brief':
416 if mode == 'brief':
411 # only first line
417 # only first line
412 if fn.__doc__:
418 if fn.__doc__:
413 fndoc = fn.__doc__.split('\n',1)[0]
419 fndoc = fn.__doc__.split('\n',1)[0]
414 else:
420 else:
415 fndoc = 'No documentation'
421 fndoc = 'No documentation'
416 else:
422 else:
417 fndoc = fn.__doc__
423 fndoc = fn.__doc__.rstrip()
424
425 if mode == 'rest':
426 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
427 fname,fndoc))
428
429 else:
430 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
431 fname,fndoc))
418
432
419 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
420 fname,fndoc))
421 magic_docs = ''.join(magic_docs)
433 magic_docs = ''.join(magic_docs)
422
434
435 if mode == 'rest':
436 return "".join(rest_docs)
437
423 if mode == 'latex':
438 if mode == 'latex':
424 print self.format_latex(magic_docs)
439 print self.format_latex(magic_docs)
425 return
440 return
426 else:
441 else:
427 magic_docs = self.format_screen(magic_docs)
442 magic_docs = self.format_screen(magic_docs)
428 if mode == 'brief':
443 if mode == 'brief':
429 return magic_docs
444 return magic_docs
430
445
431 outmsg = """
446 outmsg = """
432 IPython's 'magic' functions
447 IPython's 'magic' functions
433 ===========================
448 ===========================
434
449
435 The magic function system provides a series of functions which allow you to
450 The magic function system provides a series of functions which allow you to
436 control the behavior of IPython itself, plus a lot of system-type
451 control the behavior of IPython itself, plus a lot of system-type
437 features. All these functions are prefixed with a % character, but parameters
452 features. All these functions are prefixed with a % character, but parameters
438 are given without parentheses or quotes.
453 are given without parentheses or quotes.
439
454
440 NOTE: If you have 'automagic' enabled (via the command line option or with the
455 NOTE: If you have 'automagic' enabled (via the command line option or with the
441 %automagic function), you don't need to type in the % explicitly. By default,
456 %automagic function), you don't need to type in the % explicitly. By default,
442 IPython ships with automagic on, so you should only rarely need the % escape.
457 IPython ships with automagic on, so you should only rarely need the % escape.
443
458
444 Example: typing '%cd mydir' (without the quotes) changes you working directory
459 Example: typing '%cd mydir' (without the quotes) changes you working directory
445 to 'mydir', if it exists.
460 to 'mydir', if it exists.
446
461
447 You can define your own magic functions to extend the system. See the supplied
462 You can define your own magic functions to extend the system. See the supplied
448 ipythonrc and example-magic.py files for details (in your ipython
463 ipythonrc and example-magic.py files for details (in your ipython
449 configuration directory, typically $HOME/.ipython/).
464 configuration directory, typically $HOME/.ipython/).
450
465
451 You can also define your own aliased names for magic functions. In your
466 You can also define your own aliased names for magic functions. In your
452 ipythonrc file, placing a line like:
467 ipythonrc file, placing a line like:
453
468
454 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
469 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
455
470
456 will define %pf as a new name for %profile.
471 will define %pf as a new name for %profile.
457
472
458 You can also call magics in code using the ipmagic() function, which IPython
473 You can also call magics in code using the ipmagic() function, which IPython
459 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
460
475
461 For a list of the available magic functions, use %lsmagic. For a description
476 For a list of the available magic functions, use %lsmagic. For a description
462 of any of them, type %magic_name?, e.g. '%cd?'.
477 of any of them, type %magic_name?, e.g. '%cd?'.
463
478
464 Currently the magic system has the following functions:\n"""
479 Currently the magic system has the following functions:\n"""
465
480
466 mesc = self.shell.ESC_MAGIC
481 mesc = self.shell.ESC_MAGIC
467 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
468 "\n\n%s%s\n\n%s" % (outmsg,
483 "\n\n%s%s\n\n%s" % (outmsg,
469 magic_docs,mesc,mesc,
484 magic_docs,mesc,mesc,
470 (' '+mesc).join(self.lsmagic()),
485 (' '+mesc).join(self.lsmagic()),
471 Magic.auto_status[self.shell.rc.automagic] ) )
486 Magic.auto_status[self.shell.rc.automagic] ) )
472
487
473 page(outmsg,screen_lines=self.shell.rc.screen_length)
488 page(outmsg,screen_lines=self.shell.rc.screen_length)
474
489
475
490
476 def magic_autoindent(self, parameter_s = ''):
491 def magic_autoindent(self, parameter_s = ''):
477 """Toggle autoindent on/off (if available)."""
492 """Toggle autoindent on/off (if available)."""
478
493
479 self.shell.set_autoindent()
494 self.shell.set_autoindent()
480 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
495 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
481
496
482
497
483 def magic_automagic(self, parameter_s = ''):
498 def magic_automagic(self, parameter_s = ''):
484 """Make magic functions callable without having to type the initial %.
499 """Make magic functions callable without having to type the initial %.
485
500
486 Without argumentsl toggles on/off (when off, you must call it as
501 Without argumentsl toggles on/off (when off, you must call it as
487 %automagic, of course). With arguments it sets the value, and you can
502 %automagic, of course). With arguments it sets the value, and you can
488 use any of (case insensitive):
503 use any of (case insensitive):
489
504
490 - on,1,True: to activate
505 - on,1,True: to activate
491
506
492 - off,0,False: to deactivate.
507 - off,0,False: to deactivate.
493
508
494 Note that magic functions have lowest priority, so if there's a
509 Note that magic functions have lowest priority, so if there's a
495 variable whose name collides with that of a magic fn, automagic won't
510 variable whose name collides with that of a magic fn, automagic won't
496 work for that function (you get the variable instead). However, if you
511 work for that function (you get the variable instead). However, if you
497 delete the variable (del var), the previously shadowed magic function
512 delete the variable (del var), the previously shadowed magic function
498 becomes visible to automagic again."""
513 becomes visible to automagic again."""
499
514
500 rc = self.shell.rc
515 rc = self.shell.rc
501 arg = parameter_s.lower()
516 arg = parameter_s.lower()
502 if parameter_s in ('on','1','true'):
517 if parameter_s in ('on','1','true'):
503 rc.automagic = True
518 rc.automagic = True
504 elif parameter_s in ('off','0','false'):
519 elif parameter_s in ('off','0','false'):
505 rc.automagic = False
520 rc.automagic = False
506 else:
521 else:
507 rc.automagic = not rc.automagic
522 rc.automagic = not rc.automagic
508 print '\n' + Magic.auto_status[rc.automagic]
523 print '\n' + Magic.auto_status[rc.automagic]
509
524
510
525
511 def magic_autocall(self, parameter_s = ''):
526 def magic_autocall(self, parameter_s = ''):
512 """Make functions callable without having to type parentheses.
527 """Make functions callable without having to type parentheses.
513
528
514 Usage:
529 Usage:
515
530
516 %autocall [mode]
531 %autocall [mode]
517
532
518 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
533 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
519 value is toggled on and off (remembering the previous state).
534 value is toggled on and off (remembering the previous state).
520
535
521 In more detail, these values mean:
536 In more detail, these values mean:
522
537
523 0 -> fully disabled
538 0 -> fully disabled
524
539
525 1 -> active, but do not apply if there are no arguments on the line.
540 1 -> active, but do not apply if there are no arguments on the line.
526
541
527 In this mode, you get:
542 In this mode, you get:
528
543
529 In [1]: callable
544 In [1]: callable
530 Out[1]: <built-in function callable>
545 Out[1]: <built-in function callable>
531
546
532 In [2]: callable 'hello'
547 In [2]: callable 'hello'
533 ------> callable('hello')
548 ------> callable('hello')
534 Out[2]: False
549 Out[2]: False
535
550
536 2 -> Active always. Even if no arguments are present, the callable
551 2 -> Active always. Even if no arguments are present, the callable
537 object is called:
552 object is called:
538
553
539 In [4]: callable
554 In [4]: callable
540 ------> callable()
555 ------> callable()
541
556
542 Note that even with autocall off, you can still use '/' at the start of
557 Note that even with autocall off, you can still use '/' at the start of
543 a line to treat the first argument on the command line as a function
558 a line to treat the first argument on the command line as a function
544 and add parentheses to it:
559 and add parentheses to it:
545
560
546 In [8]: /str 43
561 In [8]: /str 43
547 ------> str(43)
562 ------> str(43)
548 Out[8]: '43'
563 Out[8]: '43'
549 """
564 """
550
565
551 rc = self.shell.rc
566 rc = self.shell.rc
552
567
553 if parameter_s:
568 if parameter_s:
554 arg = int(parameter_s)
569 arg = int(parameter_s)
555 else:
570 else:
556 arg = 'toggle'
571 arg = 'toggle'
557
572
558 if not arg in (0,1,2,'toggle'):
573 if not arg in (0,1,2,'toggle'):
559 error('Valid modes: (0->Off, 1->Smart, 2->Full')
574 error('Valid modes: (0->Off, 1->Smart, 2->Full')
560 return
575 return
561
576
562 if arg in (0,1,2):
577 if arg in (0,1,2):
563 rc.autocall = arg
578 rc.autocall = arg
564 else: # toggle
579 else: # toggle
565 if rc.autocall:
580 if rc.autocall:
566 self._magic_state.autocall_save = rc.autocall
581 self._magic_state.autocall_save = rc.autocall
567 rc.autocall = 0
582 rc.autocall = 0
568 else:
583 else:
569 try:
584 try:
570 rc.autocall = self._magic_state.autocall_save
585 rc.autocall = self._magic_state.autocall_save
571 except AttributeError:
586 except AttributeError:
572 rc.autocall = self._magic_state.autocall_save = 1
587 rc.autocall = self._magic_state.autocall_save = 1
573
588
574 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
589 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
575
590
576 def magic_system_verbose(self, parameter_s = ''):
591 def magic_system_verbose(self, parameter_s = ''):
577 """Set verbose printing of system calls.
592 """Set verbose printing of system calls.
578
593
579 If called without an argument, act as a toggle"""
594 If called without an argument, act as a toggle"""
580
595
581 if parameter_s:
596 if parameter_s:
582 val = bool(eval(parameter_s))
597 val = bool(eval(parameter_s))
583 else:
598 else:
584 val = None
599 val = None
585
600
586 self.shell.rc_set_toggle('system_verbose',val)
601 self.shell.rc_set_toggle('system_verbose',val)
587 print "System verbose printing is:",\
602 print "System verbose printing is:",\
588 ['OFF','ON'][self.shell.rc.system_verbose]
603 ['OFF','ON'][self.shell.rc.system_verbose]
589
604
590
605
591 def magic_page(self, parameter_s=''):
606 def magic_page(self, parameter_s=''):
592 """Pretty print the object and display it through a pager.
607 """Pretty print the object and display it through a pager.
593
608
594 %page [options] OBJECT
609 %page [options] OBJECT
595
610
596 If no object is given, use _ (last output).
611 If no object is given, use _ (last output).
597
612
598 Options:
613 Options:
599
614
600 -r: page str(object), don't pretty-print it."""
615 -r: page str(object), don't pretty-print it."""
601
616
602 # After a function contributed by Olivier Aubert, slightly modified.
617 # After a function contributed by Olivier Aubert, slightly modified.
603
618
604 # Process options/args
619 # Process options/args
605 opts,args = self.parse_options(parameter_s,'r')
620 opts,args = self.parse_options(parameter_s,'r')
606 raw = 'r' in opts
621 raw = 'r' in opts
607
622
608 oname = args and args or '_'
623 oname = args and args or '_'
609 info = self._ofind(oname)
624 info = self._ofind(oname)
610 if info['found']:
625 if info['found']:
611 txt = (raw and str or pformat)( info['obj'] )
626 txt = (raw and str or pformat)( info['obj'] )
612 page(txt)
627 page(txt)
613 else:
628 else:
614 print 'Object `%s` not found' % oname
629 print 'Object `%s` not found' % oname
615
630
616 def magic_profile(self, parameter_s=''):
631 def magic_profile(self, parameter_s=''):
617 """Print your currently active IPyhton profile."""
632 """Print your currently active IPyhton profile."""
618 if self.shell.rc.profile:
633 if self.shell.rc.profile:
619 printpl('Current IPython profile: $self.shell.rc.profile.')
634 printpl('Current IPython profile: $self.shell.rc.profile.')
620 else:
635 else:
621 print 'No profile active.'
636 print 'No profile active.'
622
637
623 def magic_pinfo(self, parameter_s='', namespaces=None):
638 def magic_pinfo(self, parameter_s='', namespaces=None):
624 """Provide detailed information about an object.
639 """Provide detailed information about an object.
625
640
626 '%pinfo object' is just a synonym for object? or ?object."""
641 '%pinfo object' is just a synonym for object? or ?object."""
627
642
628 #print 'pinfo par: <%s>' % parameter_s # dbg
643 #print 'pinfo par: <%s>' % parameter_s # dbg
629
644
630
645
631 # detail_level: 0 -> obj? , 1 -> obj??
646 # detail_level: 0 -> obj? , 1 -> obj??
632 detail_level = 0
647 detail_level = 0
633 # We need to detect if we got called as 'pinfo pinfo foo', which can
648 # We need to detect if we got called as 'pinfo pinfo foo', which can
634 # happen if the user types 'pinfo foo?' at the cmd line.
649 # happen if the user types 'pinfo foo?' at the cmd line.
635 pinfo,qmark1,oname,qmark2 = \
650 pinfo,qmark1,oname,qmark2 = \
636 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
651 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
637 if pinfo or qmark1 or qmark2:
652 if pinfo or qmark1 or qmark2:
638 detail_level = 1
653 detail_level = 1
639 if "*" in oname:
654 if "*" in oname:
640 self.magic_psearch(oname)
655 self.magic_psearch(oname)
641 else:
656 else:
642 self._inspect('pinfo', oname, detail_level=detail_level,
657 self._inspect('pinfo', oname, detail_level=detail_level,
643 namespaces=namespaces)
658 namespaces=namespaces)
644
659
645 def magic_pdef(self, parameter_s='', namespaces=None):
660 def magic_pdef(self, parameter_s='', namespaces=None):
646 """Print the definition header for any callable object.
661 """Print the definition header for any callable object.
647
662
648 If the object is a class, print the constructor information."""
663 If the object is a class, print the constructor information."""
649 self._inspect('pdef',parameter_s, namespaces)
664 self._inspect('pdef',parameter_s, namespaces)
650
665
651 def magic_pdoc(self, parameter_s='', namespaces=None):
666 def magic_pdoc(self, parameter_s='', namespaces=None):
652 """Print the docstring for an object.
667 """Print the docstring for an object.
653
668
654 If the given object is a class, it will print both the class and the
669 If the given object is a class, it will print both the class and the
655 constructor docstrings."""
670 constructor docstrings."""
656 self._inspect('pdoc',parameter_s, namespaces)
671 self._inspect('pdoc',parameter_s, namespaces)
657
672
658 def magic_psource(self, parameter_s='', namespaces=None):
673 def magic_psource(self, parameter_s='', namespaces=None):
659 """Print (or run through pager) the source code for an object."""
674 """Print (or run through pager) the source code for an object."""
660 self._inspect('psource',parameter_s, namespaces)
675 self._inspect('psource',parameter_s, namespaces)
661
676
662 def magic_pfile(self, parameter_s=''):
677 def magic_pfile(self, parameter_s=''):
663 """Print (or run through pager) the file where an object is defined.
678 """Print (or run through pager) the file where an object is defined.
664
679
665 The file opens at the line where the object definition begins. IPython
680 The file opens at the line where the object definition begins. IPython
666 will honor the environment variable PAGER if set, and otherwise will
681 will honor the environment variable PAGER if set, and otherwise will
667 do its best to print the file in a convenient form.
682 do its best to print the file in a convenient form.
668
683
669 If the given argument is not an object currently defined, IPython will
684 If the given argument is not an object currently defined, IPython will
670 try to interpret it as a filename (automatically adding a .py extension
685 try to interpret it as a filename (automatically adding a .py extension
671 if needed). You can thus use %pfile as a syntax highlighting code
686 if needed). You can thus use %pfile as a syntax highlighting code
672 viewer."""
687 viewer."""
673
688
674 # first interpret argument as an object name
689 # first interpret argument as an object name
675 out = self._inspect('pfile',parameter_s)
690 out = self._inspect('pfile',parameter_s)
676 # if not, try the input as a filename
691 # if not, try the input as a filename
677 if out == 'not found':
692 if out == 'not found':
678 try:
693 try:
679 filename = get_py_filename(parameter_s)
694 filename = get_py_filename(parameter_s)
680 except IOError,msg:
695 except IOError,msg:
681 print msg
696 print msg
682 return
697 return
683 page(self.shell.inspector.format(file(filename).read()))
698 page(self.shell.inspector.format(file(filename).read()))
684
699
685 def _inspect(self,meth,oname,namespaces=None,**kw):
700 def _inspect(self,meth,oname,namespaces=None,**kw):
686 """Generic interface to the inspector system.
701 """Generic interface to the inspector system.
687
702
688 This function is meant to be called by pdef, pdoc & friends."""
703 This function is meant to be called by pdef, pdoc & friends."""
689
704
690 #oname = oname.strip()
705 #oname = oname.strip()
691 #print '1- oname: <%r>' % oname # dbg
706 #print '1- oname: <%r>' % oname # dbg
692 try:
707 try:
693 oname = oname.strip().encode('ascii')
708 oname = oname.strip().encode('ascii')
694 #print '2- oname: <%r>' % oname # dbg
709 #print '2- oname: <%r>' % oname # dbg
695 except UnicodeEncodeError:
710 except UnicodeEncodeError:
696 print 'Python identifiers can only contain ascii characters.'
711 print 'Python identifiers can only contain ascii characters.'
697 return 'not found'
712 return 'not found'
698
713
699 info = Struct(self._ofind(oname, namespaces))
714 info = Struct(self._ofind(oname, namespaces))
700
715
701 if info.found:
716 if info.found:
702 try:
717 try:
703 IPython.generics.inspect_object(info.obj)
718 IPython.generics.inspect_object(info.obj)
704 return
719 return
705 except IPython.ipapi.TryNext:
720 except IPython.ipapi.TryNext:
706 pass
721 pass
707 # Get the docstring of the class property if it exists.
722 # Get the docstring of the class property if it exists.
708 path = oname.split('.')
723 path = oname.split('.')
709 root = '.'.join(path[:-1])
724 root = '.'.join(path[:-1])
710 if info.parent is not None:
725 if info.parent is not None:
711 try:
726 try:
712 target = getattr(info.parent, '__class__')
727 target = getattr(info.parent, '__class__')
713 # The object belongs to a class instance.
728 # The object belongs to a class instance.
714 try:
729 try:
715 target = getattr(target, path[-1])
730 target = getattr(target, path[-1])
716 # The class defines the object.
731 # The class defines the object.
717 if isinstance(target, property):
732 if isinstance(target, property):
718 oname = root + '.__class__.' + path[-1]
733 oname = root + '.__class__.' + path[-1]
719 info = Struct(self._ofind(oname))
734 info = Struct(self._ofind(oname))
720 except AttributeError: pass
735 except AttributeError: pass
721 except AttributeError: pass
736 except AttributeError: pass
722
737
723 pmethod = getattr(self.shell.inspector,meth)
738 pmethod = getattr(self.shell.inspector,meth)
724 formatter = info.ismagic and self.format_screen or None
739 formatter = info.ismagic and self.format_screen or None
725 if meth == 'pdoc':
740 if meth == 'pdoc':
726 pmethod(info.obj,oname,formatter)
741 pmethod(info.obj,oname,formatter)
727 elif meth == 'pinfo':
742 elif meth == 'pinfo':
728 pmethod(info.obj,oname,formatter,info,**kw)
743 pmethod(info.obj,oname,formatter,info,**kw)
729 else:
744 else:
730 pmethod(info.obj,oname)
745 pmethod(info.obj,oname)
731 else:
746 else:
732 print 'Object `%s` not found.' % oname
747 print 'Object `%s` not found.' % oname
733 return 'not found' # so callers can take other action
748 return 'not found' # so callers can take other action
734
749
735 def magic_psearch(self, parameter_s=''):
750 def magic_psearch(self, parameter_s=''):
736 """Search for object in namespaces by wildcard.
751 """Search for object in namespaces by wildcard.
737
752
738 %psearch [options] PATTERN [OBJECT TYPE]
753 %psearch [options] PATTERN [OBJECT TYPE]
739
754
740 Note: ? can be used as a synonym for %psearch, at the beginning or at
755 Note: ? can be used as a synonym for %psearch, at the beginning or at
741 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
756 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
742 rest of the command line must be unchanged (options come first), so
757 rest of the command line must be unchanged (options come first), so
743 for example the following forms are equivalent
758 for example the following forms are equivalent
744
759
745 %psearch -i a* function
760 %psearch -i a* function
746 -i a* function?
761 -i a* function?
747 ?-i a* function
762 ?-i a* function
748
763
749 Arguments:
764 Arguments:
750
765
751 PATTERN
766 PATTERN
752
767
753 where PATTERN is a string containing * as a wildcard similar to its
768 where PATTERN is a string containing * as a wildcard similar to its
754 use in a shell. The pattern is matched in all namespaces on the
769 use in a shell. The pattern is matched in all namespaces on the
755 search path. By default objects starting with a single _ are not
770 search path. By default objects starting with a single _ are not
756 matched, many IPython generated objects have a single
771 matched, many IPython generated objects have a single
757 underscore. The default is case insensitive matching. Matching is
772 underscore. The default is case insensitive matching. Matching is
758 also done on the attributes of objects and not only on the objects
773 also done on the attributes of objects and not only on the objects
759 in a module.
774 in a module.
760
775
761 [OBJECT TYPE]
776 [OBJECT TYPE]
762
777
763 Is the name of a python type from the types module. The name is
778 Is the name of a python type from the types module. The name is
764 given in lowercase without the ending type, ex. StringType is
779 given in lowercase without the ending type, ex. StringType is
765 written string. By adding a type here only objects matching the
780 written string. By adding a type here only objects matching the
766 given type are matched. Using all here makes the pattern match all
781 given type are matched. Using all here makes the pattern match all
767 types (this is the default).
782 types (this is the default).
768
783
769 Options:
784 Options:
770
785
771 -a: makes the pattern match even objects whose names start with a
786 -a: makes the pattern match even objects whose names start with a
772 single underscore. These names are normally ommitted from the
787 single underscore. These names are normally ommitted from the
773 search.
788 search.
774
789
775 -i/-c: make the pattern case insensitive/sensitive. If neither of
790 -i/-c: make the pattern case insensitive/sensitive. If neither of
776 these options is given, the default is read from your ipythonrc
791 these options is given, the default is read from your ipythonrc
777 file. The option name which sets this value is
792 file. The option name which sets this value is
778 'wildcards_case_sensitive'. If this option is not specified in your
793 'wildcards_case_sensitive'. If this option is not specified in your
779 ipythonrc file, IPython's internal default is to do a case sensitive
794 ipythonrc file, IPython's internal default is to do a case sensitive
780 search.
795 search.
781
796
782 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
797 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
783 specifiy can be searched in any of the following namespaces:
798 specifiy can be searched in any of the following namespaces:
784 'builtin', 'user', 'user_global','internal', 'alias', where
799 'builtin', 'user', 'user_global','internal', 'alias', where
785 'builtin' and 'user' are the search defaults. Note that you should
800 'builtin' and 'user' are the search defaults. Note that you should
786 not use quotes when specifying namespaces.
801 not use quotes when specifying namespaces.
787
802
788 'Builtin' contains the python module builtin, 'user' contains all
803 'Builtin' contains the python module builtin, 'user' contains all
789 user data, 'alias' only contain the shell aliases and no python
804 user data, 'alias' only contain the shell aliases and no python
790 objects, 'internal' contains objects used by IPython. The
805 objects, 'internal' contains objects used by IPython. The
791 'user_global' namespace is only used by embedded IPython instances,
806 'user_global' namespace is only used by embedded IPython instances,
792 and it contains module-level globals. You can add namespaces to the
807 and it contains module-level globals. You can add namespaces to the
793 search with -s or exclude them with -e (these options can be given
808 search with -s or exclude them with -e (these options can be given
794 more than once).
809 more than once).
795
810
796 Examples:
811 Examples:
797
812
798 %psearch a* -> objects beginning with an a
813 %psearch a* -> objects beginning with an a
799 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
814 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
800 %psearch a* function -> all functions beginning with an a
815 %psearch a* function -> all functions beginning with an a
801 %psearch re.e* -> objects beginning with an e in module re
816 %psearch re.e* -> objects beginning with an e in module re
802 %psearch r*.e* -> objects that start with e in modules starting in r
817 %psearch r*.e* -> objects that start with e in modules starting in r
803 %psearch r*.* string -> all strings in modules beginning with r
818 %psearch r*.* string -> all strings in modules beginning with r
804
819
805 Case sensitve search:
820 Case sensitve search:
806
821
807 %psearch -c a* list all object beginning with lower case a
822 %psearch -c a* list all object beginning with lower case a
808
823
809 Show objects beginning with a single _:
824 Show objects beginning with a single _:
810
825
811 %psearch -a _* list objects beginning with a single underscore"""
826 %psearch -a _* list objects beginning with a single underscore"""
812 try:
827 try:
813 parameter_s = parameter_s.encode('ascii')
828 parameter_s = parameter_s.encode('ascii')
814 except UnicodeEncodeError:
829 except UnicodeEncodeError:
815 print 'Python identifiers can only contain ascii characters.'
830 print 'Python identifiers can only contain ascii characters.'
816 return
831 return
817
832
818 # default namespaces to be searched
833 # default namespaces to be searched
819 def_search = ['user','builtin']
834 def_search = ['user','builtin']
820
835
821 # Process options/args
836 # Process options/args
822 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
837 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
823 opt = opts.get
838 opt = opts.get
824 shell = self.shell
839 shell = self.shell
825 psearch = shell.inspector.psearch
840 psearch = shell.inspector.psearch
826
841
827 # select case options
842 # select case options
828 if opts.has_key('i'):
843 if opts.has_key('i'):
829 ignore_case = True
844 ignore_case = True
830 elif opts.has_key('c'):
845 elif opts.has_key('c'):
831 ignore_case = False
846 ignore_case = False
832 else:
847 else:
833 ignore_case = not shell.rc.wildcards_case_sensitive
848 ignore_case = not shell.rc.wildcards_case_sensitive
834
849
835 # Build list of namespaces to search from user options
850 # Build list of namespaces to search from user options
836 def_search.extend(opt('s',[]))
851 def_search.extend(opt('s',[]))
837 ns_exclude = ns_exclude=opt('e',[])
852 ns_exclude = ns_exclude=opt('e',[])
838 ns_search = [nm for nm in def_search if nm not in ns_exclude]
853 ns_search = [nm for nm in def_search if nm not in ns_exclude]
839
854
840 # Call the actual search
855 # Call the actual search
841 try:
856 try:
842 psearch(args,shell.ns_table,ns_search,
857 psearch(args,shell.ns_table,ns_search,
843 show_all=opt('a'),ignore_case=ignore_case)
858 show_all=opt('a'),ignore_case=ignore_case)
844 except:
859 except:
845 shell.showtraceback()
860 shell.showtraceback()
846
861
847 def magic_who_ls(self, parameter_s=''):
862 def magic_who_ls(self, parameter_s=''):
848 """Return a sorted list of all interactive variables.
863 """Return a sorted list of all interactive variables.
849
864
850 If arguments are given, only variables of types matching these
865 If arguments are given, only variables of types matching these
851 arguments are returned."""
866 arguments are returned."""
852
867
853 user_ns = self.shell.user_ns
868 user_ns = self.shell.user_ns
854 internal_ns = self.shell.internal_ns
869 internal_ns = self.shell.internal_ns
855 user_config_ns = self.shell.user_config_ns
870 user_config_ns = self.shell.user_config_ns
856 out = []
871 out = []
857 typelist = parameter_s.split()
872 typelist = parameter_s.split()
858
873
859 for i in user_ns:
874 for i in user_ns:
860 if not (i.startswith('_') or i.startswith('_i')) \
875 if not (i.startswith('_') or i.startswith('_i')) \
861 and not (i in internal_ns or i in user_config_ns):
876 and not (i in internal_ns or i in user_config_ns):
862 if typelist:
877 if typelist:
863 if type(user_ns[i]).__name__ in typelist:
878 if type(user_ns[i]).__name__ in typelist:
864 out.append(i)
879 out.append(i)
865 else:
880 else:
866 out.append(i)
881 out.append(i)
867 out.sort()
882 out.sort()
868 return out
883 return out
869
884
870 def magic_who(self, parameter_s=''):
885 def magic_who(self, parameter_s=''):
871 """Print all interactive variables, with some minimal formatting.
886 """Print all interactive variables, with some minimal formatting.
872
887
873 If any arguments are given, only variables whose type matches one of
888 If any arguments are given, only variables whose type matches one of
874 these are printed. For example:
889 these are printed. For example:
875
890
876 %who function str
891 %who function str
877
892
878 will only list functions and strings, excluding all other types of
893 will only list functions and strings, excluding all other types of
879 variables. To find the proper type names, simply use type(var) at a
894 variables. To find the proper type names, simply use type(var) at a
880 command line to see how python prints type names. For example:
895 command line to see how python prints type names. For example:
881
896
882 In [1]: type('hello')\\
897 In [1]: type('hello')\\
883 Out[1]: <type 'str'>
898 Out[1]: <type 'str'>
884
899
885 indicates that the type name for strings is 'str'.
900 indicates that the type name for strings is 'str'.
886
901
887 %who always excludes executed names loaded through your configuration
902 %who always excludes executed names loaded through your configuration
888 file and things which are internal to IPython.
903 file and things which are internal to IPython.
889
904
890 This is deliberate, as typically you may load many modules and the
905 This is deliberate, as typically you may load many modules and the
891 purpose of %who is to show you only what you've manually defined."""
906 purpose of %who is to show you only what you've manually defined."""
892
907
893 varlist = self.magic_who_ls(parameter_s)
908 varlist = self.magic_who_ls(parameter_s)
894 if not varlist:
909 if not varlist:
895 if parameter_s:
910 if parameter_s:
896 print 'No variables match your requested type.'
911 print 'No variables match your requested type.'
897 else:
912 else:
898 print 'Interactive namespace is empty.'
913 print 'Interactive namespace is empty.'
899 return
914 return
900
915
901 # if we have variables, move on...
916 # if we have variables, move on...
902 count = 0
917 count = 0
903 for i in varlist:
918 for i in varlist:
904 print i+'\t',
919 print i+'\t',
905 count += 1
920 count += 1
906 if count > 8:
921 if count > 8:
907 count = 0
922 count = 0
908 print
923 print
909 print
924 print
910
925
911 def magic_whos(self, parameter_s=''):
926 def magic_whos(self, parameter_s=''):
912 """Like %who, but gives some extra information about each variable.
927 """Like %who, but gives some extra information about each variable.
913
928
914 The same type filtering of %who can be applied here.
929 The same type filtering of %who can be applied here.
915
930
916 For all variables, the type is printed. Additionally it prints:
931 For all variables, the type is printed. Additionally it prints:
917
932
918 - For {},[],(): their length.
933 - For {},[],(): their length.
919
934
920 - For numpy and Numeric arrays, a summary with shape, number of
935 - For numpy and Numeric arrays, a summary with shape, number of
921 elements, typecode and size in memory.
936 elements, typecode and size in memory.
922
937
923 - Everything else: a string representation, snipping their middle if
938 - Everything else: a string representation, snipping their middle if
924 too long."""
939 too long."""
925
940
926 varnames = self.magic_who_ls(parameter_s)
941 varnames = self.magic_who_ls(parameter_s)
927 if not varnames:
942 if not varnames:
928 if parameter_s:
943 if parameter_s:
929 print 'No variables match your requested type.'
944 print 'No variables match your requested type.'
930 else:
945 else:
931 print 'Interactive namespace is empty.'
946 print 'Interactive namespace is empty.'
932 return
947 return
933
948
934 # if we have variables, move on...
949 # if we have variables, move on...
935
950
936 # for these types, show len() instead of data:
951 # for these types, show len() instead of data:
937 seq_types = [types.DictType,types.ListType,types.TupleType]
952 seq_types = [types.DictType,types.ListType,types.TupleType]
938
953
939 # for numpy/Numeric arrays, display summary info
954 # for numpy/Numeric arrays, display summary info
940 try:
955 try:
941 import numpy
956 import numpy
942 except ImportError:
957 except ImportError:
943 ndarray_type = None
958 ndarray_type = None
944 else:
959 else:
945 ndarray_type = numpy.ndarray.__name__
960 ndarray_type = numpy.ndarray.__name__
946 try:
961 try:
947 import Numeric
962 import Numeric
948 except ImportError:
963 except ImportError:
949 array_type = None
964 array_type = None
950 else:
965 else:
951 array_type = Numeric.ArrayType.__name__
966 array_type = Numeric.ArrayType.__name__
952
967
953 # Find all variable names and types so we can figure out column sizes
968 # Find all variable names and types so we can figure out column sizes
954 def get_vars(i):
969 def get_vars(i):
955 return self.shell.user_ns[i]
970 return self.shell.user_ns[i]
956
971
957 # some types are well known and can be shorter
972 # some types are well known and can be shorter
958 abbrevs = {'IPython.macro.Macro' : 'Macro'}
973 abbrevs = {'IPython.macro.Macro' : 'Macro'}
959 def type_name(v):
974 def type_name(v):
960 tn = type(v).__name__
975 tn = type(v).__name__
961 return abbrevs.get(tn,tn)
976 return abbrevs.get(tn,tn)
962
977
963 varlist = map(get_vars,varnames)
978 varlist = map(get_vars,varnames)
964
979
965 typelist = []
980 typelist = []
966 for vv in varlist:
981 for vv in varlist:
967 tt = type_name(vv)
982 tt = type_name(vv)
968
983
969 if tt=='instance':
984 if tt=='instance':
970 typelist.append( abbrevs.get(str(vv.__class__),
985 typelist.append( abbrevs.get(str(vv.__class__),
971 str(vv.__class__)))
986 str(vv.__class__)))
972 else:
987 else:
973 typelist.append(tt)
988 typelist.append(tt)
974
989
975 # column labels and # of spaces as separator
990 # column labels and # of spaces as separator
976 varlabel = 'Variable'
991 varlabel = 'Variable'
977 typelabel = 'Type'
992 typelabel = 'Type'
978 datalabel = 'Data/Info'
993 datalabel = 'Data/Info'
979 colsep = 3
994 colsep = 3
980 # variable format strings
995 # variable format strings
981 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
996 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
982 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
997 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
983 aformat = "%s: %s elems, type `%s`, %s bytes"
998 aformat = "%s: %s elems, type `%s`, %s bytes"
984 # find the size of the columns to format the output nicely
999 # find the size of the columns to format the output nicely
985 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1000 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
986 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1001 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
987 # table header
1002 # table header
988 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1003 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
989 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1004 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
990 # and the table itself
1005 # and the table itself
991 kb = 1024
1006 kb = 1024
992 Mb = 1048576 # kb**2
1007 Mb = 1048576 # kb**2
993 for vname,var,vtype in zip(varnames,varlist,typelist):
1008 for vname,var,vtype in zip(varnames,varlist,typelist):
994 print itpl(vformat),
1009 print itpl(vformat),
995 if vtype in seq_types:
1010 if vtype in seq_types:
996 print len(var)
1011 print len(var)
997 elif vtype in [array_type,ndarray_type]:
1012 elif vtype in [array_type,ndarray_type]:
998 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1013 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
999 if vtype==ndarray_type:
1014 if vtype==ndarray_type:
1000 # numpy
1015 # numpy
1001 vsize = var.size
1016 vsize = var.size
1002 vbytes = vsize*var.itemsize
1017 vbytes = vsize*var.itemsize
1003 vdtype = var.dtype
1018 vdtype = var.dtype
1004 else:
1019 else:
1005 # Numeric
1020 # Numeric
1006 vsize = Numeric.size(var)
1021 vsize = Numeric.size(var)
1007 vbytes = vsize*var.itemsize()
1022 vbytes = vsize*var.itemsize()
1008 vdtype = var.typecode()
1023 vdtype = var.typecode()
1009
1024
1010 if vbytes < 100000:
1025 if vbytes < 100000:
1011 print aformat % (vshape,vsize,vdtype,vbytes)
1026 print aformat % (vshape,vsize,vdtype,vbytes)
1012 else:
1027 else:
1013 print aformat % (vshape,vsize,vdtype,vbytes),
1028 print aformat % (vshape,vsize,vdtype,vbytes),
1014 if vbytes < Mb:
1029 if vbytes < Mb:
1015 print '(%s kb)' % (vbytes/kb,)
1030 print '(%s kb)' % (vbytes/kb,)
1016 else:
1031 else:
1017 print '(%s Mb)' % (vbytes/Mb,)
1032 print '(%s Mb)' % (vbytes/Mb,)
1018 else:
1033 else:
1019 try:
1034 try:
1020 vstr = str(var)
1035 vstr = str(var)
1021 except UnicodeEncodeError:
1036 except UnicodeEncodeError:
1022 vstr = unicode(var).encode(sys.getdefaultencoding(),
1037 vstr = unicode(var).encode(sys.getdefaultencoding(),
1023 'backslashreplace')
1038 'backslashreplace')
1024 vstr = vstr.replace('\n','\\n')
1039 vstr = vstr.replace('\n','\\n')
1025 if len(vstr) < 50:
1040 if len(vstr) < 50:
1026 print vstr
1041 print vstr
1027 else:
1042 else:
1028 printpl(vfmt_short)
1043 printpl(vfmt_short)
1029
1044
1030 def magic_reset(self, parameter_s=''):
1045 def magic_reset(self, parameter_s=''):
1031 """Resets the namespace by removing all names defined by the user.
1046 """Resets the namespace by removing all names defined by the user.
1032
1047
1033 Input/Output history are left around in case you need them."""
1048 Input/Output history are left around in case you need them."""
1034
1049
1035 ans = self.shell.ask_yes_no(
1050 ans = self.shell.ask_yes_no(
1036 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1051 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1037 if not ans:
1052 if not ans:
1038 print 'Nothing done.'
1053 print 'Nothing done.'
1039 return
1054 return
1040 user_ns = self.shell.user_ns
1055 user_ns = self.shell.user_ns
1041 for i in self.magic_who_ls():
1056 for i in self.magic_who_ls():
1042 del(user_ns[i])
1057 del(user_ns[i])
1043
1058
1044 # Also flush the private list of module references kept for script
1059 # Also flush the private list of module references kept for script
1045 # execution protection
1060 # execution protection
1046 self.shell._user_main_modules[:] = []
1061 self.shell._user_main_modules[:] = []
1047
1062
1048 def magic_logstart(self,parameter_s=''):
1063 def magic_logstart(self,parameter_s=''):
1049 """Start logging anywhere in a session.
1064 """Start logging anywhere in a session.
1050
1065
1051 %logstart [-o|-r|-t] [log_name [log_mode]]
1066 %logstart [-o|-r|-t] [log_name [log_mode]]
1052
1067
1053 If no name is given, it defaults to a file named 'ipython_log.py' in your
1068 If no name is given, it defaults to a file named 'ipython_log.py' in your
1054 current directory, in 'rotate' mode (see below).
1069 current directory, in 'rotate' mode (see below).
1055
1070
1056 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1071 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1057 history up to that point and then continues logging.
1072 history up to that point and then continues logging.
1058
1073
1059 %logstart takes a second optional parameter: logging mode. This can be one
1074 %logstart takes a second optional parameter: logging mode. This can be one
1060 of (note that the modes are given unquoted):\\
1075 of (note that the modes are given unquoted):\\
1061 append: well, that says it.\\
1076 append: well, that says it.\\
1062 backup: rename (if exists) to name~ and start name.\\
1077 backup: rename (if exists) to name~ and start name.\\
1063 global: single logfile in your home dir, appended to.\\
1078 global: single logfile in your home dir, appended to.\\
1064 over : overwrite existing log.\\
1079 over : overwrite existing log.\\
1065 rotate: create rotating logs name.1~, name.2~, etc.
1080 rotate: create rotating logs name.1~, name.2~, etc.
1066
1081
1067 Options:
1082 Options:
1068
1083
1069 -o: log also IPython's output. In this mode, all commands which
1084 -o: log also IPython's output. In this mode, all commands which
1070 generate an Out[NN] prompt are recorded to the logfile, right after
1085 generate an Out[NN] prompt are recorded to the logfile, right after
1071 their corresponding input line. The output lines are always
1086 their corresponding input line. The output lines are always
1072 prepended with a '#[Out]# ' marker, so that the log remains valid
1087 prepended with a '#[Out]# ' marker, so that the log remains valid
1073 Python code.
1088 Python code.
1074
1089
1075 Since this marker is always the same, filtering only the output from
1090 Since this marker is always the same, filtering only the output from
1076 a log is very easy, using for example a simple awk call:
1091 a log is very easy, using for example a simple awk call:
1077
1092
1078 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1093 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1079
1094
1080 -r: log 'raw' input. Normally, IPython's logs contain the processed
1095 -r: log 'raw' input. Normally, IPython's logs contain the processed
1081 input, so that user lines are logged in their final form, converted
1096 input, so that user lines are logged in their final form, converted
1082 into valid Python. For example, %Exit is logged as
1097 into valid Python. For example, %Exit is logged as
1083 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1098 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1084 exactly as typed, with no transformations applied.
1099 exactly as typed, with no transformations applied.
1085
1100
1086 -t: put timestamps before each input line logged (these are put in
1101 -t: put timestamps before each input line logged (these are put in
1087 comments)."""
1102 comments)."""
1088
1103
1089 opts,par = self.parse_options(parameter_s,'ort')
1104 opts,par = self.parse_options(parameter_s,'ort')
1090 log_output = 'o' in opts
1105 log_output = 'o' in opts
1091 log_raw_input = 'r' in opts
1106 log_raw_input = 'r' in opts
1092 timestamp = 't' in opts
1107 timestamp = 't' in opts
1093
1108
1094 rc = self.shell.rc
1109 rc = self.shell.rc
1095 logger = self.shell.logger
1110 logger = self.shell.logger
1096
1111
1097 # if no args are given, the defaults set in the logger constructor by
1112 # if no args are given, the defaults set in the logger constructor by
1098 # ipytohn remain valid
1113 # ipytohn remain valid
1099 if par:
1114 if par:
1100 try:
1115 try:
1101 logfname,logmode = par.split()
1116 logfname,logmode = par.split()
1102 except:
1117 except:
1103 logfname = par
1118 logfname = par
1104 logmode = 'backup'
1119 logmode = 'backup'
1105 else:
1120 else:
1106 logfname = logger.logfname
1121 logfname = logger.logfname
1107 logmode = logger.logmode
1122 logmode = logger.logmode
1108 # put logfname into rc struct as if it had been called on the command
1123 # put logfname into rc struct as if it had been called on the command
1109 # line, so it ends up saved in the log header Save it in case we need
1124 # line, so it ends up saved in the log header Save it in case we need
1110 # to restore it...
1125 # to restore it...
1111 old_logfile = rc.opts.get('logfile','')
1126 old_logfile = rc.opts.get('logfile','')
1112 if logfname:
1127 if logfname:
1113 logfname = os.path.expanduser(logfname)
1128 logfname = os.path.expanduser(logfname)
1114 rc.opts.logfile = logfname
1129 rc.opts.logfile = logfname
1115 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1130 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1116 try:
1131 try:
1117 started = logger.logstart(logfname,loghead,logmode,
1132 started = logger.logstart(logfname,loghead,logmode,
1118 log_output,timestamp,log_raw_input)
1133 log_output,timestamp,log_raw_input)
1119 except:
1134 except:
1120 rc.opts.logfile = old_logfile
1135 rc.opts.logfile = old_logfile
1121 warn("Couldn't start log: %s" % sys.exc_info()[1])
1136 warn("Couldn't start log: %s" % sys.exc_info()[1])
1122 else:
1137 else:
1123 # log input history up to this point, optionally interleaving
1138 # log input history up to this point, optionally interleaving
1124 # output if requested
1139 # output if requested
1125
1140
1126 if timestamp:
1141 if timestamp:
1127 # disable timestamping for the previous history, since we've
1142 # disable timestamping for the previous history, since we've
1128 # lost those already (no time machine here).
1143 # lost those already (no time machine here).
1129 logger.timestamp = False
1144 logger.timestamp = False
1130
1145
1131 if log_raw_input:
1146 if log_raw_input:
1132 input_hist = self.shell.input_hist_raw
1147 input_hist = self.shell.input_hist_raw
1133 else:
1148 else:
1134 input_hist = self.shell.input_hist
1149 input_hist = self.shell.input_hist
1135
1150
1136 if log_output:
1151 if log_output:
1137 log_write = logger.log_write
1152 log_write = logger.log_write
1138 output_hist = self.shell.output_hist
1153 output_hist = self.shell.output_hist
1139 for n in range(1,len(input_hist)-1):
1154 for n in range(1,len(input_hist)-1):
1140 log_write(input_hist[n].rstrip())
1155 log_write(input_hist[n].rstrip())
1141 if n in output_hist:
1156 if n in output_hist:
1142 log_write(repr(output_hist[n]),'output')
1157 log_write(repr(output_hist[n]),'output')
1143 else:
1158 else:
1144 logger.log_write(input_hist[1:])
1159 logger.log_write(input_hist[1:])
1145 if timestamp:
1160 if timestamp:
1146 # re-enable timestamping
1161 # re-enable timestamping
1147 logger.timestamp = True
1162 logger.timestamp = True
1148
1163
1149 print ('Activating auto-logging. '
1164 print ('Activating auto-logging. '
1150 'Current session state plus future input saved.')
1165 'Current session state plus future input saved.')
1151 logger.logstate()
1166 logger.logstate()
1152
1167
1153 def magic_logstop(self,parameter_s=''):
1168 def magic_logstop(self,parameter_s=''):
1154 """Fully stop logging and close log file.
1169 """Fully stop logging and close log file.
1155
1170
1156 In order to start logging again, a new %logstart call needs to be made,
1171 In order to start logging again, a new %logstart call needs to be made,
1157 possibly (though not necessarily) with a new filename, mode and other
1172 possibly (though not necessarily) with a new filename, mode and other
1158 options."""
1173 options."""
1159 self.logger.logstop()
1174 self.logger.logstop()
1160
1175
1161 def magic_logoff(self,parameter_s=''):
1176 def magic_logoff(self,parameter_s=''):
1162 """Temporarily stop logging.
1177 """Temporarily stop logging.
1163
1178
1164 You must have previously started logging."""
1179 You must have previously started logging."""
1165 self.shell.logger.switch_log(0)
1180 self.shell.logger.switch_log(0)
1166
1181
1167 def magic_logon(self,parameter_s=''):
1182 def magic_logon(self,parameter_s=''):
1168 """Restart logging.
1183 """Restart logging.
1169
1184
1170 This function is for restarting logging which you've temporarily
1185 This function is for restarting logging which you've temporarily
1171 stopped with %logoff. For starting logging for the first time, you
1186 stopped with %logoff. For starting logging for the first time, you
1172 must use the %logstart function, which allows you to specify an
1187 must use the %logstart function, which allows you to specify an
1173 optional log filename."""
1188 optional log filename."""
1174
1189
1175 self.shell.logger.switch_log(1)
1190 self.shell.logger.switch_log(1)
1176
1191
1177 def magic_logstate(self,parameter_s=''):
1192 def magic_logstate(self,parameter_s=''):
1178 """Print the status of the logging system."""
1193 """Print the status of the logging system."""
1179
1194
1180 self.shell.logger.logstate()
1195 self.shell.logger.logstate()
1181
1196
1182 def magic_pdb(self, parameter_s=''):
1197 def magic_pdb(self, parameter_s=''):
1183 """Control the automatic calling of the pdb interactive debugger.
1198 """Control the automatic calling of the pdb interactive debugger.
1184
1199
1185 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1200 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1186 argument it works as a toggle.
1201 argument it works as a toggle.
1187
1202
1188 When an exception is triggered, IPython can optionally call the
1203 When an exception is triggered, IPython can optionally call the
1189 interactive pdb debugger after the traceback printout. %pdb toggles
1204 interactive pdb debugger after the traceback printout. %pdb toggles
1190 this feature on and off.
1205 this feature on and off.
1191
1206
1192 The initial state of this feature is set in your ipythonrc
1207 The initial state of this feature is set in your ipythonrc
1193 configuration file (the variable is called 'pdb').
1208 configuration file (the variable is called 'pdb').
1194
1209
1195 If you want to just activate the debugger AFTER an exception has fired,
1210 If you want to just activate the debugger AFTER an exception has fired,
1196 without having to type '%pdb on' and rerunning your code, you can use
1211 without having to type '%pdb on' and rerunning your code, you can use
1197 the %debug magic."""
1212 the %debug magic."""
1198
1213
1199 par = parameter_s.strip().lower()
1214 par = parameter_s.strip().lower()
1200
1215
1201 if par:
1216 if par:
1202 try:
1217 try:
1203 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1218 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1204 except KeyError:
1219 except KeyError:
1205 print ('Incorrect argument. Use on/1, off/0, '
1220 print ('Incorrect argument. Use on/1, off/0, '
1206 'or nothing for a toggle.')
1221 'or nothing for a toggle.')
1207 return
1222 return
1208 else:
1223 else:
1209 # toggle
1224 # toggle
1210 new_pdb = not self.shell.call_pdb
1225 new_pdb = not self.shell.call_pdb
1211
1226
1212 # set on the shell
1227 # set on the shell
1213 self.shell.call_pdb = new_pdb
1228 self.shell.call_pdb = new_pdb
1214 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1229 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1215
1230
1216 def magic_debug(self, parameter_s=''):
1231 def magic_debug(self, parameter_s=''):
1217 """Activate the interactive debugger in post-mortem mode.
1232 """Activate the interactive debugger in post-mortem mode.
1218
1233
1219 If an exception has just occurred, this lets you inspect its stack
1234 If an exception has just occurred, this lets you inspect its stack
1220 frames interactively. Note that this will always work only on the last
1235 frames interactively. Note that this will always work only on the last
1221 traceback that occurred, so you must call this quickly after an
1236 traceback that occurred, so you must call this quickly after an
1222 exception that you wish to inspect has fired, because if another one
1237 exception that you wish to inspect has fired, because if another one
1223 occurs, it clobbers the previous one.
1238 occurs, it clobbers the previous one.
1224
1239
1225 If you want IPython to automatically do this on every exception, see
1240 If you want IPython to automatically do this on every exception, see
1226 the %pdb magic for more details.
1241 the %pdb magic for more details.
1227 """
1242 """
1228
1243
1229 self.shell.debugger(force=True)
1244 self.shell.debugger(force=True)
1230
1245
1231 def magic_prun(self, parameter_s ='',user_mode=1,
1246 def magic_prun(self, parameter_s ='',user_mode=1,
1232 opts=None,arg_lst=None,prog_ns=None):
1247 opts=None,arg_lst=None,prog_ns=None):
1233
1248
1234 """Run a statement through the python code profiler.
1249 """Run a statement through the python code profiler.
1235
1250
1236 Usage:\\
1251 Usage:\\
1237 %prun [options] statement
1252 %prun [options] statement
1238
1253
1239 The given statement (which doesn't require quote marks) is run via the
1254 The given statement (which doesn't require quote marks) is run via the
1240 python profiler in a manner similar to the profile.run() function.
1255 python profiler in a manner similar to the profile.run() function.
1241 Namespaces are internally managed to work correctly; profile.run
1256 Namespaces are internally managed to work correctly; profile.run
1242 cannot be used in IPython because it makes certain assumptions about
1257 cannot be used in IPython because it makes certain assumptions about
1243 namespaces which do not hold under IPython.
1258 namespaces which do not hold under IPython.
1244
1259
1245 Options:
1260 Options:
1246
1261
1247 -l <limit>: you can place restrictions on what or how much of the
1262 -l <limit>: you can place restrictions on what or how much of the
1248 profile gets printed. The limit value can be:
1263 profile gets printed. The limit value can be:
1249
1264
1250 * A string: only information for function names containing this string
1265 * A string: only information for function names containing this string
1251 is printed.
1266 is printed.
1252
1267
1253 * An integer: only these many lines are printed.
1268 * An integer: only these many lines are printed.
1254
1269
1255 * A float (between 0 and 1): this fraction of the report is printed
1270 * A float (between 0 and 1): this fraction of the report is printed
1256 (for example, use a limit of 0.4 to see the topmost 40% only).
1271 (for example, use a limit of 0.4 to see the topmost 40% only).
1257
1272
1258 You can combine several limits with repeated use of the option. For
1273 You can combine several limits with repeated use of the option. For
1259 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1274 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1260 information about class constructors.
1275 information about class constructors.
1261
1276
1262 -r: return the pstats.Stats object generated by the profiling. This
1277 -r: return the pstats.Stats object generated by the profiling. This
1263 object has all the information about the profile in it, and you can
1278 object has all the information about the profile in it, and you can
1264 later use it for further analysis or in other functions.
1279 later use it for further analysis or in other functions.
1265
1280
1266 -s <key>: sort profile by given key. You can provide more than one key
1281 -s <key>: sort profile by given key. You can provide more than one key
1267 by using the option several times: '-s key1 -s key2 -s key3...'. The
1282 by using the option several times: '-s key1 -s key2 -s key3...'. The
1268 default sorting key is 'time'.
1283 default sorting key is 'time'.
1269
1284
1270 The following is copied verbatim from the profile documentation
1285 The following is copied verbatim from the profile documentation
1271 referenced below:
1286 referenced below:
1272
1287
1273 When more than one key is provided, additional keys are used as
1288 When more than one key is provided, additional keys are used as
1274 secondary criteria when the there is equality in all keys selected
1289 secondary criteria when the there is equality in all keys selected
1275 before them.
1290 before them.
1276
1291
1277 Abbreviations can be used for any key names, as long as the
1292 Abbreviations can be used for any key names, as long as the
1278 abbreviation is unambiguous. The following are the keys currently
1293 abbreviation is unambiguous. The following are the keys currently
1279 defined:
1294 defined:
1280
1295
1281 Valid Arg Meaning\\
1296 Valid Arg Meaning\\
1282 "calls" call count\\
1297 "calls" call count\\
1283 "cumulative" cumulative time\\
1298 "cumulative" cumulative time\\
1284 "file" file name\\
1299 "file" file name\\
1285 "module" file name\\
1300 "module" file name\\
1286 "pcalls" primitive call count\\
1301 "pcalls" primitive call count\\
1287 "line" line number\\
1302 "line" line number\\
1288 "name" function name\\
1303 "name" function name\\
1289 "nfl" name/file/line\\
1304 "nfl" name/file/line\\
1290 "stdname" standard name\\
1305 "stdname" standard name\\
1291 "time" internal time
1306 "time" internal time
1292
1307
1293 Note that all sorts on statistics are in descending order (placing
1308 Note that all sorts on statistics are in descending order (placing
1294 most time consuming items first), where as name, file, and line number
1309 most time consuming items first), where as name, file, and line number
1295 searches are in ascending order (i.e., alphabetical). The subtle
1310 searches are in ascending order (i.e., alphabetical). The subtle
1296 distinction between "nfl" and "stdname" is that the standard name is a
1311 distinction between "nfl" and "stdname" is that the standard name is a
1297 sort of the name as printed, which means that the embedded line
1312 sort of the name as printed, which means that the embedded line
1298 numbers get compared in an odd way. For example, lines 3, 20, and 40
1313 numbers get compared in an odd way. For example, lines 3, 20, and 40
1299 would (if the file names were the same) appear in the string order
1314 would (if the file names were the same) appear in the string order
1300 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1315 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1301 line numbers. In fact, sort_stats("nfl") is the same as
1316 line numbers. In fact, sort_stats("nfl") is the same as
1302 sort_stats("name", "file", "line").
1317 sort_stats("name", "file", "line").
1303
1318
1304 -T <filename>: save profile results as shown on screen to a text
1319 -T <filename>: save profile results as shown on screen to a text
1305 file. The profile is still shown on screen.
1320 file. The profile is still shown on screen.
1306
1321
1307 -D <filename>: save (via dump_stats) profile statistics to given
1322 -D <filename>: save (via dump_stats) profile statistics to given
1308 filename. This data is in a format understod by the pstats module, and
1323 filename. This data is in a format understod by the pstats module, and
1309 is generated by a call to the dump_stats() method of profile
1324 is generated by a call to the dump_stats() method of profile
1310 objects. The profile is still shown on screen.
1325 objects. The profile is still shown on screen.
1311
1326
1312 If you want to run complete programs under the profiler's control, use
1327 If you want to run complete programs under the profiler's control, use
1313 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1328 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1314 contains profiler specific options as described here.
1329 contains profiler specific options as described here.
1315
1330
1316 You can read the complete documentation for the profile module with:\\
1331 You can read the complete documentation for the profile module with:\\
1317 In [1]: import profile; profile.help() """
1332 In [1]: import profile; profile.help() """
1318
1333
1319 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1334 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1320 # protect user quote marks
1335 # protect user quote marks
1321 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1336 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1322
1337
1323 if user_mode: # regular user call
1338 if user_mode: # regular user call
1324 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1339 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1325 list_all=1)
1340 list_all=1)
1326 namespace = self.shell.user_ns
1341 namespace = self.shell.user_ns
1327 else: # called to run a program by %run -p
1342 else: # called to run a program by %run -p
1328 try:
1343 try:
1329 filename = get_py_filename(arg_lst[0])
1344 filename = get_py_filename(arg_lst[0])
1330 except IOError,msg:
1345 except IOError,msg:
1331 error(msg)
1346 error(msg)
1332 return
1347 return
1333
1348
1334 arg_str = 'execfile(filename,prog_ns)'
1349 arg_str = 'execfile(filename,prog_ns)'
1335 namespace = locals()
1350 namespace = locals()
1336
1351
1337 opts.merge(opts_def)
1352 opts.merge(opts_def)
1338
1353
1339 prof = profile.Profile()
1354 prof = profile.Profile()
1340 try:
1355 try:
1341 prof = prof.runctx(arg_str,namespace,namespace)
1356 prof = prof.runctx(arg_str,namespace,namespace)
1342 sys_exit = ''
1357 sys_exit = ''
1343 except SystemExit:
1358 except SystemExit:
1344 sys_exit = """*** SystemExit exception caught in code being profiled."""
1359 sys_exit = """*** SystemExit exception caught in code being profiled."""
1345
1360
1346 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1361 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1347
1362
1348 lims = opts.l
1363 lims = opts.l
1349 if lims:
1364 if lims:
1350 lims = [] # rebuild lims with ints/floats/strings
1365 lims = [] # rebuild lims with ints/floats/strings
1351 for lim in opts.l:
1366 for lim in opts.l:
1352 try:
1367 try:
1353 lims.append(int(lim))
1368 lims.append(int(lim))
1354 except ValueError:
1369 except ValueError:
1355 try:
1370 try:
1356 lims.append(float(lim))
1371 lims.append(float(lim))
1357 except ValueError:
1372 except ValueError:
1358 lims.append(lim)
1373 lims.append(lim)
1359
1374
1360 # Trap output.
1375 # Trap output.
1361 stdout_trap = StringIO()
1376 stdout_trap = StringIO()
1362
1377
1363 if hasattr(stats,'stream'):
1378 if hasattr(stats,'stream'):
1364 # In newer versions of python, the stats object has a 'stream'
1379 # In newer versions of python, the stats object has a 'stream'
1365 # attribute to write into.
1380 # attribute to write into.
1366 stats.stream = stdout_trap
1381 stats.stream = stdout_trap
1367 stats.print_stats(*lims)
1382 stats.print_stats(*lims)
1368 else:
1383 else:
1369 # For older versions, we manually redirect stdout during printing
1384 # For older versions, we manually redirect stdout during printing
1370 sys_stdout = sys.stdout
1385 sys_stdout = sys.stdout
1371 try:
1386 try:
1372 sys.stdout = stdout_trap
1387 sys.stdout = stdout_trap
1373 stats.print_stats(*lims)
1388 stats.print_stats(*lims)
1374 finally:
1389 finally:
1375 sys.stdout = sys_stdout
1390 sys.stdout = sys_stdout
1376
1391
1377 output = stdout_trap.getvalue()
1392 output = stdout_trap.getvalue()
1378 output = output.rstrip()
1393 output = output.rstrip()
1379
1394
1380 page(output,screen_lines=self.shell.rc.screen_length)
1395 page(output,screen_lines=self.shell.rc.screen_length)
1381 print sys_exit,
1396 print sys_exit,
1382
1397
1383 dump_file = opts.D[0]
1398 dump_file = opts.D[0]
1384 text_file = opts.T[0]
1399 text_file = opts.T[0]
1385 if dump_file:
1400 if dump_file:
1386 prof.dump_stats(dump_file)
1401 prof.dump_stats(dump_file)
1387 print '\n*** Profile stats marshalled to file',\
1402 print '\n*** Profile stats marshalled to file',\
1388 `dump_file`+'.',sys_exit
1403 `dump_file`+'.',sys_exit
1389 if text_file:
1404 if text_file:
1390 pfile = file(text_file,'w')
1405 pfile = file(text_file,'w')
1391 pfile.write(output)
1406 pfile.write(output)
1392 pfile.close()
1407 pfile.close()
1393 print '\n*** Profile printout saved to text file',\
1408 print '\n*** Profile printout saved to text file',\
1394 `text_file`+'.',sys_exit
1409 `text_file`+'.',sys_exit
1395
1410
1396 if opts.has_key('r'):
1411 if opts.has_key('r'):
1397 return stats
1412 return stats
1398 else:
1413 else:
1399 return None
1414 return None
1400
1415
1401 def magic_run(self, parameter_s ='',runner=None):
1416 def magic_run(self, parameter_s ='',runner=None):
1402 """Run the named file inside IPython as a program.
1417 """Run the named file inside IPython as a program.
1403
1418
1404 Usage:\\
1419 Usage:\\
1405 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1420 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1406
1421
1407 Parameters after the filename are passed as command-line arguments to
1422 Parameters after the filename are passed as command-line arguments to
1408 the program (put in sys.argv). Then, control returns to IPython's
1423 the program (put in sys.argv). Then, control returns to IPython's
1409 prompt.
1424 prompt.
1410
1425
1411 This is similar to running at a system prompt:\\
1426 This is similar to running at a system prompt:\\
1412 $ python file args\\
1427 $ python file args\\
1413 but with the advantage of giving you IPython's tracebacks, and of
1428 but with the advantage of giving you IPython's tracebacks, and of
1414 loading all variables into your interactive namespace for further use
1429 loading all variables into your interactive namespace for further use
1415 (unless -p is used, see below).
1430 (unless -p is used, see below).
1416
1431
1417 The file is executed in a namespace initially consisting only of
1432 The file is executed in a namespace initially consisting only of
1418 __name__=='__main__' and sys.argv constructed as indicated. It thus
1433 __name__=='__main__' and sys.argv constructed as indicated. It thus
1419 sees its environment as if it were being run as a stand-alone program
1434 sees its environment as if it were being run as a stand-alone program
1420 (except for sharing global objects such as previously imported
1435 (except for sharing global objects such as previously imported
1421 modules). But after execution, the IPython interactive namespace gets
1436 modules). But after execution, the IPython interactive namespace gets
1422 updated with all variables defined in the program (except for __name__
1437 updated with all variables defined in the program (except for __name__
1423 and sys.argv). This allows for very convenient loading of code for
1438 and sys.argv). This allows for very convenient loading of code for
1424 interactive work, while giving each program a 'clean sheet' to run in.
1439 interactive work, while giving each program a 'clean sheet' to run in.
1425
1440
1426 Options:
1441 Options:
1427
1442
1428 -n: __name__ is NOT set to '__main__', but to the running file's name
1443 -n: __name__ is NOT set to '__main__', but to the running file's name
1429 without extension (as python does under import). This allows running
1444 without extension (as python does under import). This allows running
1430 scripts and reloading the definitions in them without calling code
1445 scripts and reloading the definitions in them without calling code
1431 protected by an ' if __name__ == "__main__" ' clause.
1446 protected by an ' if __name__ == "__main__" ' clause.
1432
1447
1433 -i: run the file in IPython's namespace instead of an empty one. This
1448 -i: run the file in IPython's namespace instead of an empty one. This
1434 is useful if you are experimenting with code written in a text editor
1449 is useful if you are experimenting with code written in a text editor
1435 which depends on variables defined interactively.
1450 which depends on variables defined interactively.
1436
1451
1437 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1452 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1438 being run. This is particularly useful if IPython is being used to
1453 being run. This is particularly useful if IPython is being used to
1439 run unittests, which always exit with a sys.exit() call. In such
1454 run unittests, which always exit with a sys.exit() call. In such
1440 cases you are interested in the output of the test results, not in
1455 cases you are interested in the output of the test results, not in
1441 seeing a traceback of the unittest module.
1456 seeing a traceback of the unittest module.
1442
1457
1443 -t: print timing information at the end of the run. IPython will give
1458 -t: print timing information at the end of the run. IPython will give
1444 you an estimated CPU time consumption for your script, which under
1459 you an estimated CPU time consumption for your script, which under
1445 Unix uses the resource module to avoid the wraparound problems of
1460 Unix uses the resource module to avoid the wraparound problems of
1446 time.clock(). Under Unix, an estimate of time spent on system tasks
1461 time.clock(). Under Unix, an estimate of time spent on system tasks
1447 is also given (for Windows platforms this is reported as 0.0).
1462 is also given (for Windows platforms this is reported as 0.0).
1448
1463
1449 If -t is given, an additional -N<N> option can be given, where <N>
1464 If -t is given, an additional -N<N> option can be given, where <N>
1450 must be an integer indicating how many times you want the script to
1465 must be an integer indicating how many times you want the script to
1451 run. The final timing report will include total and per run results.
1466 run. The final timing report will include total and per run results.
1452
1467
1453 For example (testing the script uniq_stable.py):
1468 For example (testing the script uniq_stable.py):
1454
1469
1455 In [1]: run -t uniq_stable
1470 In [1]: run -t uniq_stable
1456
1471
1457 IPython CPU timings (estimated):\\
1472 IPython CPU timings (estimated):\\
1458 User : 0.19597 s.\\
1473 User : 0.19597 s.\\
1459 System: 0.0 s.\\
1474 System: 0.0 s.\\
1460
1475
1461 In [2]: run -t -N5 uniq_stable
1476 In [2]: run -t -N5 uniq_stable
1462
1477
1463 IPython CPU timings (estimated):\\
1478 IPython CPU timings (estimated):\\
1464 Total runs performed: 5\\
1479 Total runs performed: 5\\
1465 Times : Total Per run\\
1480 Times : Total Per run\\
1466 User : 0.910862 s, 0.1821724 s.\\
1481 User : 0.910862 s, 0.1821724 s.\\
1467 System: 0.0 s, 0.0 s.
1482 System: 0.0 s, 0.0 s.
1468
1483
1469 -d: run your program under the control of pdb, the Python debugger.
1484 -d: run your program under the control of pdb, the Python debugger.
1470 This allows you to execute your program step by step, watch variables,
1485 This allows you to execute your program step by step, watch variables,
1471 etc. Internally, what IPython does is similar to calling:
1486 etc. Internally, what IPython does is similar to calling:
1472
1487
1473 pdb.run('execfile("YOURFILENAME")')
1488 pdb.run('execfile("YOURFILENAME")')
1474
1489
1475 with a breakpoint set on line 1 of your file. You can change the line
1490 with a breakpoint set on line 1 of your file. You can change the line
1476 number for this automatic breakpoint to be <N> by using the -bN option
1491 number for this automatic breakpoint to be <N> by using the -bN option
1477 (where N must be an integer). For example:
1492 (where N must be an integer). For example:
1478
1493
1479 %run -d -b40 myscript
1494 %run -d -b40 myscript
1480
1495
1481 will set the first breakpoint at line 40 in myscript.py. Note that
1496 will set the first breakpoint at line 40 in myscript.py. Note that
1482 the first breakpoint must be set on a line which actually does
1497 the first breakpoint must be set on a line which actually does
1483 something (not a comment or docstring) for it to stop execution.
1498 something (not a comment or docstring) for it to stop execution.
1484
1499
1485 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1500 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1486 first enter 'c' (without qoutes) to start execution up to the first
1501 first enter 'c' (without qoutes) to start execution up to the first
1487 breakpoint.
1502 breakpoint.
1488
1503
1489 Entering 'help' gives information about the use of the debugger. You
1504 Entering 'help' gives information about the use of the debugger. You
1490 can easily see pdb's full documentation with "import pdb;pdb.help()"
1505 can easily see pdb's full documentation with "import pdb;pdb.help()"
1491 at a prompt.
1506 at a prompt.
1492
1507
1493 -p: run program under the control of the Python profiler module (which
1508 -p: run program under the control of the Python profiler module (which
1494 prints a detailed report of execution times, function calls, etc).
1509 prints a detailed report of execution times, function calls, etc).
1495
1510
1496 You can pass other options after -p which affect the behavior of the
1511 You can pass other options after -p which affect the behavior of the
1497 profiler itself. See the docs for %prun for details.
1512 profiler itself. See the docs for %prun for details.
1498
1513
1499 In this mode, the program's variables do NOT propagate back to the
1514 In this mode, the program's variables do NOT propagate back to the
1500 IPython interactive namespace (because they remain in the namespace
1515 IPython interactive namespace (because they remain in the namespace
1501 where the profiler executes them).
1516 where the profiler executes them).
1502
1517
1503 Internally this triggers a call to %prun, see its documentation for
1518 Internally this triggers a call to %prun, see its documentation for
1504 details on the options available specifically for profiling.
1519 details on the options available specifically for profiling.
1505
1520
1506 There is one special usage for which the text above doesn't apply:
1521 There is one special usage for which the text above doesn't apply:
1507 if the filename ends with .ipy, the file is run as ipython script,
1522 if the filename ends with .ipy, the file is run as ipython script,
1508 just as if the commands were written on IPython prompt.
1523 just as if the commands were written on IPython prompt.
1509 """
1524 """
1510
1525
1511 # get arguments and set sys.argv for program to be run.
1526 # get arguments and set sys.argv for program to be run.
1512 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1527 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1513 mode='list',list_all=1)
1528 mode='list',list_all=1)
1514
1529
1515 try:
1530 try:
1516 filename = get_py_filename(arg_lst[0])
1531 filename = get_py_filename(arg_lst[0])
1517 except IndexError:
1532 except IndexError:
1518 warn('you must provide at least a filename.')
1533 warn('you must provide at least a filename.')
1519 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1534 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1520 return
1535 return
1521 except IOError,msg:
1536 except IOError,msg:
1522 error(msg)
1537 error(msg)
1523 return
1538 return
1524
1539
1525 if filename.lower().endswith('.ipy'):
1540 if filename.lower().endswith('.ipy'):
1526 self.api.runlines(open(filename).read())
1541 self.api.runlines(open(filename).read())
1527 return
1542 return
1528
1543
1529 # Control the response to exit() calls made by the script being run
1544 # Control the response to exit() calls made by the script being run
1530 exit_ignore = opts.has_key('e')
1545 exit_ignore = opts.has_key('e')
1531
1546
1532 # Make sure that the running script gets a proper sys.argv as if it
1547 # Make sure that the running script gets a proper sys.argv as if it
1533 # were run from a system shell.
1548 # were run from a system shell.
1534 save_argv = sys.argv # save it for later restoring
1549 save_argv = sys.argv # save it for later restoring
1535 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1550 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1536
1551
1537 if opts.has_key('i'):
1552 if opts.has_key('i'):
1538 # Run in user's interactive namespace
1553 # Run in user's interactive namespace
1539 prog_ns = self.shell.user_ns
1554 prog_ns = self.shell.user_ns
1540 __name__save = self.shell.user_ns['__name__']
1555 __name__save = self.shell.user_ns['__name__']
1541 prog_ns['__name__'] = '__main__'
1556 prog_ns['__name__'] = '__main__'
1542 main_mod = FakeModule(prog_ns)
1557 main_mod = FakeModule(prog_ns)
1543 else:
1558 else:
1544 # Run in a fresh, empty namespace
1559 # Run in a fresh, empty namespace
1545 if opts.has_key('n'):
1560 if opts.has_key('n'):
1546 name = os.path.splitext(os.path.basename(filename))[0]
1561 name = os.path.splitext(os.path.basename(filename))[0]
1547 else:
1562 else:
1548 name = '__main__'
1563 name = '__main__'
1549 main_mod = FakeModule()
1564 main_mod = FakeModule()
1550 prog_ns = main_mod.__dict__
1565 prog_ns = main_mod.__dict__
1551 prog_ns['__name__'] = name
1566 prog_ns['__name__'] = name
1552 # The shell MUST hold a reference to main_mod so after %run exits,
1567 # The shell MUST hold a reference to main_mod so after %run exits,
1553 # the python deletion mechanism doesn't zero it out (leaving
1568 # the python deletion mechanism doesn't zero it out (leaving
1554 # dangling references)
1569 # dangling references)
1555 self.shell._user_main_modules.append(main_mod)
1570 self.shell._user_main_modules.append(main_mod)
1556
1571
1557 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1572 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1558 # set the __file__ global in the script's namespace
1573 # set the __file__ global in the script's namespace
1559 prog_ns['__file__'] = filename
1574 prog_ns['__file__'] = filename
1560
1575
1561 # pickle fix. See iplib for an explanation. But we need to make sure
1576 # pickle fix. See iplib for an explanation. But we need to make sure
1562 # that, if we overwrite __main__, we replace it at the end
1577 # that, if we overwrite __main__, we replace it at the end
1563 if prog_ns['__name__'] == '__main__':
1578 if prog_ns['__name__'] == '__main__':
1564 restore_main = sys.modules['__main__']
1579 restore_main = sys.modules['__main__']
1565 else:
1580 else:
1566 restore_main = False
1581 restore_main = False
1567
1582
1568 sys.modules[prog_ns['__name__']] = main_mod
1583 sys.modules[prog_ns['__name__']] = main_mod
1569
1584
1570 stats = None
1585 stats = None
1571 try:
1586 try:
1572 self.shell.savehist()
1587 self.shell.savehist()
1573
1588
1574 if opts.has_key('p'):
1589 if opts.has_key('p'):
1575 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1590 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1576 else:
1591 else:
1577 if opts.has_key('d'):
1592 if opts.has_key('d'):
1578 deb = Debugger.Pdb(self.shell.rc.colors)
1593 deb = Debugger.Pdb(self.shell.rc.colors)
1579 # reset Breakpoint state, which is moronically kept
1594 # reset Breakpoint state, which is moronically kept
1580 # in a class
1595 # in a class
1581 bdb.Breakpoint.next = 1
1596 bdb.Breakpoint.next = 1
1582 bdb.Breakpoint.bplist = {}
1597 bdb.Breakpoint.bplist = {}
1583 bdb.Breakpoint.bpbynumber = [None]
1598 bdb.Breakpoint.bpbynumber = [None]
1584 # Set an initial breakpoint to stop execution
1599 # Set an initial breakpoint to stop execution
1585 maxtries = 10
1600 maxtries = 10
1586 bp = int(opts.get('b',[1])[0])
1601 bp = int(opts.get('b',[1])[0])
1587 checkline = deb.checkline(filename,bp)
1602 checkline = deb.checkline(filename,bp)
1588 if not checkline:
1603 if not checkline:
1589 for bp in range(bp+1,bp+maxtries+1):
1604 for bp in range(bp+1,bp+maxtries+1):
1590 if deb.checkline(filename,bp):
1605 if deb.checkline(filename,bp):
1591 break
1606 break
1592 else:
1607 else:
1593 msg = ("\nI failed to find a valid line to set "
1608 msg = ("\nI failed to find a valid line to set "
1594 "a breakpoint\n"
1609 "a breakpoint\n"
1595 "after trying up to line: %s.\n"
1610 "after trying up to line: %s.\n"
1596 "Please set a valid breakpoint manually "
1611 "Please set a valid breakpoint manually "
1597 "with the -b option." % bp)
1612 "with the -b option." % bp)
1598 error(msg)
1613 error(msg)
1599 return
1614 return
1600 # if we find a good linenumber, set the breakpoint
1615 # if we find a good linenumber, set the breakpoint
1601 deb.do_break('%s:%s' % (filename,bp))
1616 deb.do_break('%s:%s' % (filename,bp))
1602 # Start file run
1617 # Start file run
1603 print "NOTE: Enter 'c' at the",
1618 print "NOTE: Enter 'c' at the",
1604 print "%s prompt to start your script." % deb.prompt
1619 print "%s prompt to start your script." % deb.prompt
1605 try:
1620 try:
1606 deb.run('execfile("%s")' % filename,prog_ns)
1621 deb.run('execfile("%s")' % filename,prog_ns)
1607
1622
1608 except:
1623 except:
1609 etype, value, tb = sys.exc_info()
1624 etype, value, tb = sys.exc_info()
1610 # Skip three frames in the traceback: the %run one,
1625 # Skip three frames in the traceback: the %run one,
1611 # one inside bdb.py, and the command-line typed by the
1626 # one inside bdb.py, and the command-line typed by the
1612 # user (run by exec in pdb itself).
1627 # user (run by exec in pdb itself).
1613 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1628 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1614 else:
1629 else:
1615 if runner is None:
1630 if runner is None:
1616 runner = self.shell.safe_execfile
1631 runner = self.shell.safe_execfile
1617 if opts.has_key('t'):
1632 if opts.has_key('t'):
1618 # timed execution
1633 # timed execution
1619 try:
1634 try:
1620 nruns = int(opts['N'][0])
1635 nruns = int(opts['N'][0])
1621 if nruns < 1:
1636 if nruns < 1:
1622 error('Number of runs must be >=1')
1637 error('Number of runs must be >=1')
1623 return
1638 return
1624 except (KeyError):
1639 except (KeyError):
1625 nruns = 1
1640 nruns = 1
1626 if nruns == 1:
1641 if nruns == 1:
1627 t0 = clock2()
1642 t0 = clock2()
1628 runner(filename,prog_ns,prog_ns,
1643 runner(filename,prog_ns,prog_ns,
1629 exit_ignore=exit_ignore)
1644 exit_ignore=exit_ignore)
1630 t1 = clock2()
1645 t1 = clock2()
1631 t_usr = t1[0]-t0[0]
1646 t_usr = t1[0]-t0[0]
1632 t_sys = t1[1]-t1[1]
1647 t_sys = t1[1]-t1[1]
1633 print "\nIPython CPU timings (estimated):"
1648 print "\nIPython CPU timings (estimated):"
1634 print " User : %10s s." % t_usr
1649 print " User : %10s s." % t_usr
1635 print " System: %10s s." % t_sys
1650 print " System: %10s s." % t_sys
1636 else:
1651 else:
1637 runs = range(nruns)
1652 runs = range(nruns)
1638 t0 = clock2()
1653 t0 = clock2()
1639 for nr in runs:
1654 for nr in runs:
1640 runner(filename,prog_ns,prog_ns,
1655 runner(filename,prog_ns,prog_ns,
1641 exit_ignore=exit_ignore)
1656 exit_ignore=exit_ignore)
1642 t1 = clock2()
1657 t1 = clock2()
1643 t_usr = t1[0]-t0[0]
1658 t_usr = t1[0]-t0[0]
1644 t_sys = t1[1]-t1[1]
1659 t_sys = t1[1]-t1[1]
1645 print "\nIPython CPU timings (estimated):"
1660 print "\nIPython CPU timings (estimated):"
1646 print "Total runs performed:",nruns
1661 print "Total runs performed:",nruns
1647 print " Times : %10s %10s" % ('Total','Per run')
1662 print " Times : %10s %10s" % ('Total','Per run')
1648 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1663 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1649 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1664 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1650
1665
1651 else:
1666 else:
1652 # regular execution
1667 # regular execution
1653 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1668 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1654 if opts.has_key('i'):
1669 if opts.has_key('i'):
1655 self.shell.user_ns['__name__'] = __name__save
1670 self.shell.user_ns['__name__'] = __name__save
1656 else:
1671 else:
1657 # update IPython interactive namespace
1672 # update IPython interactive namespace
1658 del prog_ns['__name__']
1673 del prog_ns['__name__']
1659 self.shell.user_ns.update(prog_ns)
1674 self.shell.user_ns.update(prog_ns)
1660 finally:
1675 finally:
1661 sys.argv = save_argv
1676 sys.argv = save_argv
1662 if restore_main:
1677 if restore_main:
1663 sys.modules['__main__'] = restore_main
1678 sys.modules['__main__'] = restore_main
1664 self.shell.reloadhist()
1679 self.shell.reloadhist()
1665
1680
1666 return stats
1681 return stats
1667
1682
1668 def magic_runlog(self, parameter_s =''):
1683 def magic_runlog(self, parameter_s =''):
1669 """Run files as logs.
1684 """Run files as logs.
1670
1685
1671 Usage:\\
1686 Usage:\\
1672 %runlog file1 file2 ...
1687 %runlog file1 file2 ...
1673
1688
1674 Run the named files (treating them as log files) in sequence inside
1689 Run the named files (treating them as log files) in sequence inside
1675 the interpreter, and return to the prompt. This is much slower than
1690 the interpreter, and return to the prompt. This is much slower than
1676 %run because each line is executed in a try/except block, but it
1691 %run because each line is executed in a try/except block, but it
1677 allows running files with syntax errors in them.
1692 allows running files with syntax errors in them.
1678
1693
1679 Normally IPython will guess when a file is one of its own logfiles, so
1694 Normally IPython will guess when a file is one of its own logfiles, so
1680 you can typically use %run even for logs. This shorthand allows you to
1695 you can typically use %run even for logs. This shorthand allows you to
1681 force any file to be treated as a log file."""
1696 force any file to be treated as a log file."""
1682
1697
1683 for f in parameter_s.split():
1698 for f in parameter_s.split():
1684 self.shell.safe_execfile(f,self.shell.user_ns,
1699 self.shell.safe_execfile(f,self.shell.user_ns,
1685 self.shell.user_ns,islog=1)
1700 self.shell.user_ns,islog=1)
1686
1701
1687 def magic_timeit(self, parameter_s =''):
1702 def magic_timeit(self, parameter_s =''):
1688 """Time execution of a Python statement or expression
1703 """Time execution of a Python statement or expression
1689
1704
1690 Usage:\\
1705 Usage:\\
1691 %timeit [-n<N> -r<R> [-t|-c]] statement
1706 %timeit [-n<N> -r<R> [-t|-c]] statement
1692
1707
1693 Time execution of a Python statement or expression using the timeit
1708 Time execution of a Python statement or expression using the timeit
1694 module.
1709 module.
1695
1710
1696 Options:
1711 Options:
1697 -n<N>: execute the given statement <N> times in a loop. If this value
1712 -n<N>: execute the given statement <N> times in a loop. If this value
1698 is not given, a fitting value is chosen.
1713 is not given, a fitting value is chosen.
1699
1714
1700 -r<R>: repeat the loop iteration <R> times and take the best result.
1715 -r<R>: repeat the loop iteration <R> times and take the best result.
1701 Default: 3
1716 Default: 3
1702
1717
1703 -t: use time.time to measure the time, which is the default on Unix.
1718 -t: use time.time to measure the time, which is the default on Unix.
1704 This function measures wall time.
1719 This function measures wall time.
1705
1720
1706 -c: use time.clock to measure the time, which is the default on
1721 -c: use time.clock to measure the time, which is the default on
1707 Windows and measures wall time. On Unix, resource.getrusage is used
1722 Windows and measures wall time. On Unix, resource.getrusage is used
1708 instead and returns the CPU user time.
1723 instead and returns the CPU user time.
1709
1724
1710 -p<P>: use a precision of <P> digits to display the timing result.
1725 -p<P>: use a precision of <P> digits to display the timing result.
1711 Default: 3
1726 Default: 3
1712
1727
1713
1728
1714 Examples:\\
1729 Examples:\\
1715 In [1]: %timeit pass
1730 In [1]: %timeit pass
1716 10000000 loops, best of 3: 53.3 ns per loop
1731 10000000 loops, best of 3: 53.3 ns per loop
1717
1732
1718 In [2]: u = None
1733 In [2]: u = None
1719
1734
1720 In [3]: %timeit u is None
1735 In [3]: %timeit u is None
1721 10000000 loops, best of 3: 184 ns per loop
1736 10000000 loops, best of 3: 184 ns per loop
1722
1737
1723 In [4]: %timeit -r 4 u == None
1738 In [4]: %timeit -r 4 u == None
1724 1000000 loops, best of 4: 242 ns per loop
1739 1000000 loops, best of 4: 242 ns per loop
1725
1740
1726 In [5]: import time
1741 In [5]: import time
1727
1742
1728 In [6]: %timeit -n1 time.sleep(2)
1743 In [6]: %timeit -n1 time.sleep(2)
1729 1 loops, best of 3: 2 s per loop
1744 1 loops, best of 3: 2 s per loop
1730
1745
1731
1746
1732 The times reported by %timeit will be slightly higher than those
1747 The times reported by %timeit will be slightly higher than those
1733 reported by the timeit.py script when variables are accessed. This is
1748 reported by the timeit.py script when variables are accessed. This is
1734 due to the fact that %timeit executes the statement in the namespace
1749 due to the fact that %timeit executes the statement in the namespace
1735 of the shell, compared with timeit.py, which uses a single setup
1750 of the shell, compared with timeit.py, which uses a single setup
1736 statement to import function or create variables. Generally, the bias
1751 statement to import function or create variables. Generally, the bias
1737 does not matter as long as results from timeit.py are not mixed with
1752 does not matter as long as results from timeit.py are not mixed with
1738 those from %timeit."""
1753 those from %timeit."""
1739
1754
1740 import timeit
1755 import timeit
1741 import math
1756 import math
1742
1757
1743 units = ["s", "ms", "\xc2\xb5s", "ns"]
1758 units = ["s", "ms", "\xc2\xb5s", "ns"]
1744 scaling = [1, 1e3, 1e6, 1e9]
1759 scaling = [1, 1e3, 1e6, 1e9]
1745
1760
1746 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1761 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1747 posix=False)
1762 posix=False)
1748 if stmt == "":
1763 if stmt == "":
1749 return
1764 return
1750 timefunc = timeit.default_timer
1765 timefunc = timeit.default_timer
1751 number = int(getattr(opts, "n", 0))
1766 number = int(getattr(opts, "n", 0))
1752 repeat = int(getattr(opts, "r", timeit.default_repeat))
1767 repeat = int(getattr(opts, "r", timeit.default_repeat))
1753 precision = int(getattr(opts, "p", 3))
1768 precision = int(getattr(opts, "p", 3))
1754 if hasattr(opts, "t"):
1769 if hasattr(opts, "t"):
1755 timefunc = time.time
1770 timefunc = time.time
1756 if hasattr(opts, "c"):
1771 if hasattr(opts, "c"):
1757 timefunc = clock
1772 timefunc = clock
1758
1773
1759 timer = timeit.Timer(timer=timefunc)
1774 timer = timeit.Timer(timer=timefunc)
1760 # this code has tight coupling to the inner workings of timeit.Timer,
1775 # this code has tight coupling to the inner workings of timeit.Timer,
1761 # but is there a better way to achieve that the code stmt has access
1776 # but is there a better way to achieve that the code stmt has access
1762 # to the shell namespace?
1777 # to the shell namespace?
1763
1778
1764 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1779 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1765 'setup': "pass"}
1780 'setup': "pass"}
1766 # Track compilation time so it can be reported if too long
1781 # Track compilation time so it can be reported if too long
1767 # Minimum time above which compilation time will be reported
1782 # Minimum time above which compilation time will be reported
1768 tc_min = 0.1
1783 tc_min = 0.1
1769
1784
1770 t0 = clock()
1785 t0 = clock()
1771 code = compile(src, "<magic-timeit>", "exec")
1786 code = compile(src, "<magic-timeit>", "exec")
1772 tc = clock()-t0
1787 tc = clock()-t0
1773
1788
1774 ns = {}
1789 ns = {}
1775 exec code in self.shell.user_ns, ns
1790 exec code in self.shell.user_ns, ns
1776 timer.inner = ns["inner"]
1791 timer.inner = ns["inner"]
1777
1792
1778 if number == 0:
1793 if number == 0:
1779 # determine number so that 0.2 <= total time < 2.0
1794 # determine number so that 0.2 <= total time < 2.0
1780 number = 1
1795 number = 1
1781 for i in range(1, 10):
1796 for i in range(1, 10):
1782 number *= 10
1797 number *= 10
1783 if timer.timeit(number) >= 0.2:
1798 if timer.timeit(number) >= 0.2:
1784 break
1799 break
1785
1800
1786 best = min(timer.repeat(repeat, number)) / number
1801 best = min(timer.repeat(repeat, number)) / number
1787
1802
1788 if best > 0.0:
1803 if best > 0.0:
1789 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1804 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1790 else:
1805 else:
1791 order = 3
1806 order = 3
1792 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1807 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1793 precision,
1808 precision,
1794 best * scaling[order],
1809 best * scaling[order],
1795 units[order])
1810 units[order])
1796 if tc > tc_min:
1811 if tc > tc_min:
1797 print "Compiler time: %.2f s" % tc
1812 print "Compiler time: %.2f s" % tc
1798
1813
1799 def magic_time(self,parameter_s = ''):
1814 def magic_time(self,parameter_s = ''):
1800 """Time execution of a Python statement or expression.
1815 """Time execution of a Python statement or expression.
1801
1816
1802 The CPU and wall clock times are printed, and the value of the
1817 The CPU and wall clock times are printed, and the value of the
1803 expression (if any) is returned. Note that under Win32, system time
1818 expression (if any) is returned. Note that under Win32, system time
1804 is always reported as 0, since it can not be measured.
1819 is always reported as 0, since it can not be measured.
1805
1820
1806 This function provides very basic timing functionality. In Python
1821 This function provides very basic timing functionality. In Python
1807 2.3, the timeit module offers more control and sophistication, so this
1822 2.3, the timeit module offers more control and sophistication, so this
1808 could be rewritten to use it (patches welcome).
1823 could be rewritten to use it (patches welcome).
1809
1824
1810 Some examples:
1825 Some examples:
1811
1826
1812 In [1]: time 2**128
1827 In [1]: time 2**128
1813 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1828 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1814 Wall time: 0.00
1829 Wall time: 0.00
1815 Out[1]: 340282366920938463463374607431768211456L
1830 Out[1]: 340282366920938463463374607431768211456L
1816
1831
1817 In [2]: n = 1000000
1832 In [2]: n = 1000000
1818
1833
1819 In [3]: time sum(range(n))
1834 In [3]: time sum(range(n))
1820 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1835 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1821 Wall time: 1.37
1836 Wall time: 1.37
1822 Out[3]: 499999500000L
1837 Out[3]: 499999500000L
1823
1838
1824 In [4]: time print 'hello world'
1839 In [4]: time print 'hello world'
1825 hello world
1840 hello world
1826 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1841 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1827 Wall time: 0.00
1842 Wall time: 0.00
1828
1843
1829 Note that the time needed by Python to compile the given expression
1844 Note that the time needed by Python to compile the given expression
1830 will be reported if it is more than 0.1s. In this example, the
1845 will be reported if it is more than 0.1s. In this example, the
1831 actual exponentiation is done by Python at compilation time, so while
1846 actual exponentiation is done by Python at compilation time, so while
1832 the expression can take a noticeable amount of time to compute, that
1847 the expression can take a noticeable amount of time to compute, that
1833 time is purely due to the compilation:
1848 time is purely due to the compilation:
1834
1849
1835 In [5]: time 3**9999;
1850 In [5]: time 3**9999;
1836 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1851 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1837 Wall time: 0.00 s
1852 Wall time: 0.00 s
1838
1853
1839 In [6]: time 3**999999;
1854 In [6]: time 3**999999;
1840 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1855 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1841 Wall time: 0.00 s
1856 Wall time: 0.00 s
1842 Compiler : 0.78 s
1857 Compiler : 0.78 s
1843 """
1858 """
1844
1859
1845 # fail immediately if the given expression can't be compiled
1860 # fail immediately if the given expression can't be compiled
1846
1861
1847 expr = self.shell.prefilter(parameter_s,False)
1862 expr = self.shell.prefilter(parameter_s,False)
1848
1863
1849 # Minimum time above which compilation time will be reported
1864 # Minimum time above which compilation time will be reported
1850 tc_min = 0.1
1865 tc_min = 0.1
1851
1866
1852 try:
1867 try:
1853 mode = 'eval'
1868 mode = 'eval'
1854 t0 = clock()
1869 t0 = clock()
1855 code = compile(expr,'<timed eval>',mode)
1870 code = compile(expr,'<timed eval>',mode)
1856 tc = clock()-t0
1871 tc = clock()-t0
1857 except SyntaxError:
1872 except SyntaxError:
1858 mode = 'exec'
1873 mode = 'exec'
1859 t0 = clock()
1874 t0 = clock()
1860 code = compile(expr,'<timed exec>',mode)
1875 code = compile(expr,'<timed exec>',mode)
1861 tc = clock()-t0
1876 tc = clock()-t0
1862 # skew measurement as little as possible
1877 # skew measurement as little as possible
1863 glob = self.shell.user_ns
1878 glob = self.shell.user_ns
1864 clk = clock2
1879 clk = clock2
1865 wtime = time.time
1880 wtime = time.time
1866 # time execution
1881 # time execution
1867 wall_st = wtime()
1882 wall_st = wtime()
1868 if mode=='eval':
1883 if mode=='eval':
1869 st = clk()
1884 st = clk()
1870 out = eval(code,glob)
1885 out = eval(code,glob)
1871 end = clk()
1886 end = clk()
1872 else:
1887 else:
1873 st = clk()
1888 st = clk()
1874 exec code in glob
1889 exec code in glob
1875 end = clk()
1890 end = clk()
1876 out = None
1891 out = None
1877 wall_end = wtime()
1892 wall_end = wtime()
1878 # Compute actual times and report
1893 # Compute actual times and report
1879 wall_time = wall_end-wall_st
1894 wall_time = wall_end-wall_st
1880 cpu_user = end[0]-st[0]
1895 cpu_user = end[0]-st[0]
1881 cpu_sys = end[1]-st[1]
1896 cpu_sys = end[1]-st[1]
1882 cpu_tot = cpu_user+cpu_sys
1897 cpu_tot = cpu_user+cpu_sys
1883 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1898 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1884 (cpu_user,cpu_sys,cpu_tot)
1899 (cpu_user,cpu_sys,cpu_tot)
1885 print "Wall time: %.2f s" % wall_time
1900 print "Wall time: %.2f s" % wall_time
1886 if tc > tc_min:
1901 if tc > tc_min:
1887 print "Compiler : %.2f s" % tc
1902 print "Compiler : %.2f s" % tc
1888 return out
1903 return out
1889
1904
1890 def magic_macro(self,parameter_s = ''):
1905 def magic_macro(self,parameter_s = ''):
1891 """Define a set of input lines as a macro for future re-execution.
1906 """Define a set of input lines as a macro for future re-execution.
1892
1907
1893 Usage:\\
1908 Usage:\\
1894 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1909 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1895
1910
1896 Options:
1911 Options:
1897
1912
1898 -r: use 'raw' input. By default, the 'processed' history is used,
1913 -r: use 'raw' input. By default, the 'processed' history is used,
1899 so that magics are loaded in their transformed version to valid
1914 so that magics are loaded in their transformed version to valid
1900 Python. If this option is given, the raw input as typed as the
1915 Python. If this option is given, the raw input as typed as the
1901 command line is used instead.
1916 command line is used instead.
1902
1917
1903 This will define a global variable called `name` which is a string
1918 This will define a global variable called `name` which is a string
1904 made of joining the slices and lines you specify (n1,n2,... numbers
1919 made of joining the slices and lines you specify (n1,n2,... numbers
1905 above) from your input history into a single string. This variable
1920 above) from your input history into a single string. This variable
1906 acts like an automatic function which re-executes those lines as if
1921 acts like an automatic function which re-executes those lines as if
1907 you had typed them. You just type 'name' at the prompt and the code
1922 you had typed them. You just type 'name' at the prompt and the code
1908 executes.
1923 executes.
1909
1924
1910 The notation for indicating number ranges is: n1-n2 means 'use line
1925 The notation for indicating number ranges is: n1-n2 means 'use line
1911 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1926 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1912 using the lines numbered 5,6 and 7.
1927 using the lines numbered 5,6 and 7.
1913
1928
1914 Note: as a 'hidden' feature, you can also use traditional python slice
1929 Note: as a 'hidden' feature, you can also use traditional python slice
1915 notation, where N:M means numbers N through M-1.
1930 notation, where N:M means numbers N through M-1.
1916
1931
1917 For example, if your history contains (%hist prints it):
1932 For example, if your history contains (%hist prints it):
1918
1933
1919 44: x=1\\
1934 44: x=1\\
1920 45: y=3\\
1935 45: y=3\\
1921 46: z=x+y\\
1936 46: z=x+y\\
1922 47: print x\\
1937 47: print x\\
1923 48: a=5\\
1938 48: a=5\\
1924 49: print 'x',x,'y',y\\
1939 49: print 'x',x,'y',y\\
1925
1940
1926 you can create a macro with lines 44 through 47 (included) and line 49
1941 you can create a macro with lines 44 through 47 (included) and line 49
1927 called my_macro with:
1942 called my_macro with:
1928
1943
1929 In [51]: %macro my_macro 44-47 49
1944 In [51]: %macro my_macro 44-47 49
1930
1945
1931 Now, typing `my_macro` (without quotes) will re-execute all this code
1946 Now, typing `my_macro` (without quotes) will re-execute all this code
1932 in one pass.
1947 in one pass.
1933
1948
1934 You don't need to give the line-numbers in order, and any given line
1949 You don't need to give the line-numbers in order, and any given line
1935 number can appear multiple times. You can assemble macros with any
1950 number can appear multiple times. You can assemble macros with any
1936 lines from your input history in any order.
1951 lines from your input history in any order.
1937
1952
1938 The macro is a simple object which holds its value in an attribute,
1953 The macro is a simple object which holds its value in an attribute,
1939 but IPython's display system checks for macros and executes them as
1954 but IPython's display system checks for macros and executes them as
1940 code instead of printing them when you type their name.
1955 code instead of printing them when you type their name.
1941
1956
1942 You can view a macro's contents by explicitly printing it with:
1957 You can view a macro's contents by explicitly printing it with:
1943
1958
1944 'print macro_name'.
1959 'print macro_name'.
1945
1960
1946 For one-off cases which DON'T contain magic function calls in them you
1961 For one-off cases which DON'T contain magic function calls in them you
1947 can obtain similar results by explicitly executing slices from your
1962 can obtain similar results by explicitly executing slices from your
1948 input history with:
1963 input history with:
1949
1964
1950 In [60]: exec In[44:48]+In[49]"""
1965 In [60]: exec In[44:48]+In[49]"""
1951
1966
1952 opts,args = self.parse_options(parameter_s,'r',mode='list')
1967 opts,args = self.parse_options(parameter_s,'r',mode='list')
1953 if not args:
1968 if not args:
1954 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1969 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1955 macs.sort()
1970 macs.sort()
1956 return macs
1971 return macs
1957 if len(args) == 1:
1972 if len(args) == 1:
1958 raise UsageError(
1973 raise UsageError(
1959 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1974 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1960 name,ranges = args[0], args[1:]
1975 name,ranges = args[0], args[1:]
1961
1976
1962 #print 'rng',ranges # dbg
1977 #print 'rng',ranges # dbg
1963 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1978 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1964 macro = Macro(lines)
1979 macro = Macro(lines)
1965 self.shell.user_ns.update({name:macro})
1980 self.shell.user_ns.update({name:macro})
1966 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1981 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1967 print 'Macro contents:'
1982 print 'Macro contents:'
1968 print macro,
1983 print macro,
1969
1984
1970 def magic_save(self,parameter_s = ''):
1985 def magic_save(self,parameter_s = ''):
1971 """Save a set of lines to a given filename.
1986 """Save a set of lines to a given filename.
1972
1987
1973 Usage:\\
1988 Usage:\\
1974 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1989 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1975
1990
1976 Options:
1991 Options:
1977
1992
1978 -r: use 'raw' input. By default, the 'processed' history is used,
1993 -r: use 'raw' input. By default, the 'processed' history is used,
1979 so that magics are loaded in their transformed version to valid
1994 so that magics are loaded in their transformed version to valid
1980 Python. If this option is given, the raw input as typed as the
1995 Python. If this option is given, the raw input as typed as the
1981 command line is used instead.
1996 command line is used instead.
1982
1997
1983 This function uses the same syntax as %macro for line extraction, but
1998 This function uses the same syntax as %macro for line extraction, but
1984 instead of creating a macro it saves the resulting string to the
1999 instead of creating a macro it saves the resulting string to the
1985 filename you specify.
2000 filename you specify.
1986
2001
1987 It adds a '.py' extension to the file if you don't do so yourself, and
2002 It adds a '.py' extension to the file if you don't do so yourself, and
1988 it asks for confirmation before overwriting existing files."""
2003 it asks for confirmation before overwriting existing files."""
1989
2004
1990 opts,args = self.parse_options(parameter_s,'r',mode='list')
2005 opts,args = self.parse_options(parameter_s,'r',mode='list')
1991 fname,ranges = args[0], args[1:]
2006 fname,ranges = args[0], args[1:]
1992 if not fname.endswith('.py'):
2007 if not fname.endswith('.py'):
1993 fname += '.py'
2008 fname += '.py'
1994 if os.path.isfile(fname):
2009 if os.path.isfile(fname):
1995 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2010 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1996 if ans.lower() not in ['y','yes']:
2011 if ans.lower() not in ['y','yes']:
1997 print 'Operation cancelled.'
2012 print 'Operation cancelled.'
1998 return
2013 return
1999 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2014 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2000 f = file(fname,'w')
2015 f = file(fname,'w')
2001 f.write(cmds)
2016 f.write(cmds)
2002 f.close()
2017 f.close()
2003 print 'The following commands were written to file `%s`:' % fname
2018 print 'The following commands were written to file `%s`:' % fname
2004 print cmds
2019 print cmds
2005
2020
2006 def _edit_macro(self,mname,macro):
2021 def _edit_macro(self,mname,macro):
2007 """open an editor with the macro data in a file"""
2022 """open an editor with the macro data in a file"""
2008 filename = self.shell.mktempfile(macro.value)
2023 filename = self.shell.mktempfile(macro.value)
2009 self.shell.hooks.editor(filename)
2024 self.shell.hooks.editor(filename)
2010
2025
2011 # and make a new macro object, to replace the old one
2026 # and make a new macro object, to replace the old one
2012 mfile = open(filename)
2027 mfile = open(filename)
2013 mvalue = mfile.read()
2028 mvalue = mfile.read()
2014 mfile.close()
2029 mfile.close()
2015 self.shell.user_ns[mname] = Macro(mvalue)
2030 self.shell.user_ns[mname] = Macro(mvalue)
2016
2031
2017 def magic_ed(self,parameter_s=''):
2032 def magic_ed(self,parameter_s=''):
2018 """Alias to %edit."""
2033 """Alias to %edit."""
2019 return self.magic_edit(parameter_s)
2034 return self.magic_edit(parameter_s)
2020
2035
2021 def magic_edit(self,parameter_s='',last_call=['','']):
2036 def magic_edit(self,parameter_s='',last_call=['','']):
2022 """Bring up an editor and execute the resulting code.
2037 """Bring up an editor and execute the resulting code.
2023
2038
2024 Usage:
2039 Usage:
2025 %edit [options] [args]
2040 %edit [options] [args]
2026
2041
2027 %edit runs IPython's editor hook. The default version of this hook is
2042 %edit runs IPython's editor hook. The default version of this hook is
2028 set to call the __IPYTHON__.rc.editor command. This is read from your
2043 set to call the __IPYTHON__.rc.editor command. This is read from your
2029 environment variable $EDITOR. If this isn't found, it will default to
2044 environment variable $EDITOR. If this isn't found, it will default to
2030 vi under Linux/Unix and to notepad under Windows. See the end of this
2045 vi under Linux/Unix and to notepad under Windows. See the end of this
2031 docstring for how to change the editor hook.
2046 docstring for how to change the editor hook.
2032
2047
2033 You can also set the value of this editor via the command line option
2048 You can also set the value of this editor via the command line option
2034 '-editor' or in your ipythonrc file. This is useful if you wish to use
2049 '-editor' or in your ipythonrc file. This is useful if you wish to use
2035 specifically for IPython an editor different from your typical default
2050 specifically for IPython an editor different from your typical default
2036 (and for Windows users who typically don't set environment variables).
2051 (and for Windows users who typically don't set environment variables).
2037
2052
2038 This command allows you to conveniently edit multi-line code right in
2053 This command allows you to conveniently edit multi-line code right in
2039 your IPython session.
2054 your IPython session.
2040
2055
2041 If called without arguments, %edit opens up an empty editor with a
2056 If called without arguments, %edit opens up an empty editor with a
2042 temporary file and will execute the contents of this file when you
2057 temporary file and will execute the contents of this file when you
2043 close it (don't forget to save it!).
2058 close it (don't forget to save it!).
2044
2059
2045
2060
2046 Options:
2061 Options:
2047
2062
2048 -n <number>: open the editor at a specified line number. By default,
2063 -n <number>: open the editor at a specified line number. By default,
2049 the IPython editor hook uses the unix syntax 'editor +N filename', but
2064 the IPython editor hook uses the unix syntax 'editor +N filename', but
2050 you can configure this by providing your own modified hook if your
2065 you can configure this by providing your own modified hook if your
2051 favorite editor supports line-number specifications with a different
2066 favorite editor supports line-number specifications with a different
2052 syntax.
2067 syntax.
2053
2068
2054 -p: this will call the editor with the same data as the previous time
2069 -p: this will call the editor with the same data as the previous time
2055 it was used, regardless of how long ago (in your current session) it
2070 it was used, regardless of how long ago (in your current session) it
2056 was.
2071 was.
2057
2072
2058 -r: use 'raw' input. This option only applies to input taken from the
2073 -r: use 'raw' input. This option only applies to input taken from the
2059 user's history. By default, the 'processed' history is used, so that
2074 user's history. By default, the 'processed' history is used, so that
2060 magics are loaded in their transformed version to valid Python. If
2075 magics are loaded in their transformed version to valid Python. If
2061 this option is given, the raw input as typed as the command line is
2076 this option is given, the raw input as typed as the command line is
2062 used instead. When you exit the editor, it will be executed by
2077 used instead. When you exit the editor, it will be executed by
2063 IPython's own processor.
2078 IPython's own processor.
2064
2079
2065 -x: do not execute the edited code immediately upon exit. This is
2080 -x: do not execute the edited code immediately upon exit. This is
2066 mainly useful if you are editing programs which need to be called with
2081 mainly useful if you are editing programs which need to be called with
2067 command line arguments, which you can then do using %run.
2082 command line arguments, which you can then do using %run.
2068
2083
2069
2084
2070 Arguments:
2085 Arguments:
2071
2086
2072 If arguments are given, the following possibilites exist:
2087 If arguments are given, the following possibilites exist:
2073
2088
2074 - The arguments are numbers or pairs of colon-separated numbers (like
2089 - The arguments are numbers or pairs of colon-separated numbers (like
2075 1 4:8 9). These are interpreted as lines of previous input to be
2090 1 4:8 9). These are interpreted as lines of previous input to be
2076 loaded into the editor. The syntax is the same of the %macro command.
2091 loaded into the editor. The syntax is the same of the %macro command.
2077
2092
2078 - If the argument doesn't start with a number, it is evaluated as a
2093 - If the argument doesn't start with a number, it is evaluated as a
2079 variable and its contents loaded into the editor. You can thus edit
2094 variable and its contents loaded into the editor. You can thus edit
2080 any string which contains python code (including the result of
2095 any string which contains python code (including the result of
2081 previous edits).
2096 previous edits).
2082
2097
2083 - If the argument is the name of an object (other than a string),
2098 - If the argument is the name of an object (other than a string),
2084 IPython will try to locate the file where it was defined and open the
2099 IPython will try to locate the file where it was defined and open the
2085 editor at the point where it is defined. You can use `%edit function`
2100 editor at the point where it is defined. You can use `%edit function`
2086 to load an editor exactly at the point where 'function' is defined,
2101 to load an editor exactly at the point where 'function' is defined,
2087 edit it and have the file be executed automatically.
2102 edit it and have the file be executed automatically.
2088
2103
2089 If the object is a macro (see %macro for details), this opens up your
2104 If the object is a macro (see %macro for details), this opens up your
2090 specified editor with a temporary file containing the macro's data.
2105 specified editor with a temporary file containing the macro's data.
2091 Upon exit, the macro is reloaded with the contents of the file.
2106 Upon exit, the macro is reloaded with the contents of the file.
2092
2107
2093 Note: opening at an exact line is only supported under Unix, and some
2108 Note: opening at an exact line is only supported under Unix, and some
2094 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2109 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2095 '+NUMBER' parameter necessary for this feature. Good editors like
2110 '+NUMBER' parameter necessary for this feature. Good editors like
2096 (X)Emacs, vi, jed, pico and joe all do.
2111 (X)Emacs, vi, jed, pico and joe all do.
2097
2112
2098 - If the argument is not found as a variable, IPython will look for a
2113 - If the argument is not found as a variable, IPython will look for a
2099 file with that name (adding .py if necessary) and load it into the
2114 file with that name (adding .py if necessary) and load it into the
2100 editor. It will execute its contents with execfile() when you exit,
2115 editor. It will execute its contents with execfile() when you exit,
2101 loading any code in the file into your interactive namespace.
2116 loading any code in the file into your interactive namespace.
2102
2117
2103 After executing your code, %edit will return as output the code you
2118 After executing your code, %edit will return as output the code you
2104 typed in the editor (except when it was an existing file). This way
2119 typed in the editor (except when it was an existing file). This way
2105 you can reload the code in further invocations of %edit as a variable,
2120 you can reload the code in further invocations of %edit as a variable,
2106 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2121 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2107 the output.
2122 the output.
2108
2123
2109 Note that %edit is also available through the alias %ed.
2124 Note that %edit is also available through the alias %ed.
2110
2125
2111 This is an example of creating a simple function inside the editor and
2126 This is an example of creating a simple function inside the editor and
2112 then modifying it. First, start up the editor:
2127 then modifying it. First, start up the editor:
2113
2128
2114 In [1]: ed\\
2129 In [1]: ed\\
2115 Editing... done. Executing edited code...\\
2130 Editing... done. Executing edited code...\\
2116 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2131 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2117
2132
2118 We can then call the function foo():
2133 We can then call the function foo():
2119
2134
2120 In [2]: foo()\\
2135 In [2]: foo()\\
2121 foo() was defined in an editing session
2136 foo() was defined in an editing session
2122
2137
2123 Now we edit foo. IPython automatically loads the editor with the
2138 Now we edit foo. IPython automatically loads the editor with the
2124 (temporary) file where foo() was previously defined:
2139 (temporary) file where foo() was previously defined:
2125
2140
2126 In [3]: ed foo\\
2141 In [3]: ed foo\\
2127 Editing... done. Executing edited code...
2142 Editing... done. Executing edited code...
2128
2143
2129 And if we call foo() again we get the modified version:
2144 And if we call foo() again we get the modified version:
2130
2145
2131 In [4]: foo()\\
2146 In [4]: foo()\\
2132 foo() has now been changed!
2147 foo() has now been changed!
2133
2148
2134 Here is an example of how to edit a code snippet successive
2149 Here is an example of how to edit a code snippet successive
2135 times. First we call the editor:
2150 times. First we call the editor:
2136
2151
2137 In [8]: ed\\
2152 In [8]: ed\\
2138 Editing... done. Executing edited code...\\
2153 Editing... done. Executing edited code...\\
2139 hello\\
2154 hello\\
2140 Out[8]: "print 'hello'\\n"
2155 Out[8]: "print 'hello'\\n"
2141
2156
2142 Now we call it again with the previous output (stored in _):
2157 Now we call it again with the previous output (stored in _):
2143
2158
2144 In [9]: ed _\\
2159 In [9]: ed _\\
2145 Editing... done. Executing edited code...\\
2160 Editing... done. Executing edited code...\\
2146 hello world\\
2161 hello world\\
2147 Out[9]: "print 'hello world'\\n"
2162 Out[9]: "print 'hello world'\\n"
2148
2163
2149 Now we call it with the output #8 (stored in _8, also as Out[8]):
2164 Now we call it with the output #8 (stored in _8, also as Out[8]):
2150
2165
2151 In [10]: ed _8\\
2166 In [10]: ed _8\\
2152 Editing... done. Executing edited code...\\
2167 Editing... done. Executing edited code...\\
2153 hello again\\
2168 hello again\\
2154 Out[10]: "print 'hello again'\\n"
2169 Out[10]: "print 'hello again'\\n"
2155
2170
2156
2171
2157 Changing the default editor hook:
2172 Changing the default editor hook:
2158
2173
2159 If you wish to write your own editor hook, you can put it in a
2174 If you wish to write your own editor hook, you can put it in a
2160 configuration file which you load at startup time. The default hook
2175 configuration file which you load at startup time. The default hook
2161 is defined in the IPython.hooks module, and you can use that as a
2176 is defined in the IPython.hooks module, and you can use that as a
2162 starting example for further modifications. That file also has
2177 starting example for further modifications. That file also has
2163 general instructions on how to set a new hook for use once you've
2178 general instructions on how to set a new hook for use once you've
2164 defined it."""
2179 defined it."""
2165
2180
2166 # FIXME: This function has become a convoluted mess. It needs a
2181 # FIXME: This function has become a convoluted mess. It needs a
2167 # ground-up rewrite with clean, simple logic.
2182 # ground-up rewrite with clean, simple logic.
2168
2183
2169 def make_filename(arg):
2184 def make_filename(arg):
2170 "Make a filename from the given args"
2185 "Make a filename from the given args"
2171 try:
2186 try:
2172 filename = get_py_filename(arg)
2187 filename = get_py_filename(arg)
2173 except IOError:
2188 except IOError:
2174 if args.endswith('.py'):
2189 if args.endswith('.py'):
2175 filename = arg
2190 filename = arg
2176 else:
2191 else:
2177 filename = None
2192 filename = None
2178 return filename
2193 return filename
2179
2194
2180 # custom exceptions
2195 # custom exceptions
2181 class DataIsObject(Exception): pass
2196 class DataIsObject(Exception): pass
2182
2197
2183 opts,args = self.parse_options(parameter_s,'prxn:')
2198 opts,args = self.parse_options(parameter_s,'prxn:')
2184 # Set a few locals from the options for convenience:
2199 # Set a few locals from the options for convenience:
2185 opts_p = opts.has_key('p')
2200 opts_p = opts.has_key('p')
2186 opts_r = opts.has_key('r')
2201 opts_r = opts.has_key('r')
2187
2202
2188 # Default line number value
2203 # Default line number value
2189 lineno = opts.get('n',None)
2204 lineno = opts.get('n',None)
2190
2205
2191 if opts_p:
2206 if opts_p:
2192 args = '_%s' % last_call[0]
2207 args = '_%s' % last_call[0]
2193 if not self.shell.user_ns.has_key(args):
2208 if not self.shell.user_ns.has_key(args):
2194 args = last_call[1]
2209 args = last_call[1]
2195
2210
2196 # use last_call to remember the state of the previous call, but don't
2211 # use last_call to remember the state of the previous call, but don't
2197 # let it be clobbered by successive '-p' calls.
2212 # let it be clobbered by successive '-p' calls.
2198 try:
2213 try:
2199 last_call[0] = self.shell.outputcache.prompt_count
2214 last_call[0] = self.shell.outputcache.prompt_count
2200 if not opts_p:
2215 if not opts_p:
2201 last_call[1] = parameter_s
2216 last_call[1] = parameter_s
2202 except:
2217 except:
2203 pass
2218 pass
2204
2219
2205 # by default this is done with temp files, except when the given
2220 # by default this is done with temp files, except when the given
2206 # arg is a filename
2221 # arg is a filename
2207 use_temp = 1
2222 use_temp = 1
2208
2223
2209 if re.match(r'\d',args):
2224 if re.match(r'\d',args):
2210 # Mode where user specifies ranges of lines, like in %macro.
2225 # Mode where user specifies ranges of lines, like in %macro.
2211 # This means that you can't edit files whose names begin with
2226 # This means that you can't edit files whose names begin with
2212 # numbers this way. Tough.
2227 # numbers this way. Tough.
2213 ranges = args.split()
2228 ranges = args.split()
2214 data = ''.join(self.extract_input_slices(ranges,opts_r))
2229 data = ''.join(self.extract_input_slices(ranges,opts_r))
2215 elif args.endswith('.py'):
2230 elif args.endswith('.py'):
2216 filename = make_filename(args)
2231 filename = make_filename(args)
2217 data = ''
2232 data = ''
2218 use_temp = 0
2233 use_temp = 0
2219 elif args:
2234 elif args:
2220 try:
2235 try:
2221 # Load the parameter given as a variable. If not a string,
2236 # Load the parameter given as a variable. If not a string,
2222 # process it as an object instead (below)
2237 # process it as an object instead (below)
2223
2238
2224 #print '*** args',args,'type',type(args) # dbg
2239 #print '*** args',args,'type',type(args) # dbg
2225 data = eval(args,self.shell.user_ns)
2240 data = eval(args,self.shell.user_ns)
2226 if not type(data) in StringTypes:
2241 if not type(data) in StringTypes:
2227 raise DataIsObject
2242 raise DataIsObject
2228
2243
2229 except (NameError,SyntaxError):
2244 except (NameError,SyntaxError):
2230 # given argument is not a variable, try as a filename
2245 # given argument is not a variable, try as a filename
2231 filename = make_filename(args)
2246 filename = make_filename(args)
2232 if filename is None:
2247 if filename is None:
2233 warn("Argument given (%s) can't be found as a variable "
2248 warn("Argument given (%s) can't be found as a variable "
2234 "or as a filename." % args)
2249 "or as a filename." % args)
2235 return
2250 return
2236
2251
2237 data = ''
2252 data = ''
2238 use_temp = 0
2253 use_temp = 0
2239 except DataIsObject:
2254 except DataIsObject:
2240
2255
2241 # macros have a special edit function
2256 # macros have a special edit function
2242 if isinstance(data,Macro):
2257 if isinstance(data,Macro):
2243 self._edit_macro(args,data)
2258 self._edit_macro(args,data)
2244 return
2259 return
2245
2260
2246 # For objects, try to edit the file where they are defined
2261 # For objects, try to edit the file where they are defined
2247 try:
2262 try:
2248 filename = inspect.getabsfile(data)
2263 filename = inspect.getabsfile(data)
2249 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2264 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2250 # class created by %edit? Try to find source
2265 # class created by %edit? Try to find source
2251 # by looking for method definitions instead, the
2266 # by looking for method definitions instead, the
2252 # __module__ in those classes is FakeModule.
2267 # __module__ in those classes is FakeModule.
2253 attrs = [getattr(data, aname) for aname in dir(data)]
2268 attrs = [getattr(data, aname) for aname in dir(data)]
2254 for attr in attrs:
2269 for attr in attrs:
2255 if not inspect.ismethod(attr):
2270 if not inspect.ismethod(attr):
2256 continue
2271 continue
2257 filename = inspect.getabsfile(attr)
2272 filename = inspect.getabsfile(attr)
2258 if filename and 'fakemodule' not in filename.lower():
2273 if filename and 'fakemodule' not in filename.lower():
2259 # change the attribute to be the edit target instead
2274 # change the attribute to be the edit target instead
2260 data = attr
2275 data = attr
2261 break
2276 break
2262
2277
2263 datafile = 1
2278 datafile = 1
2264 except TypeError:
2279 except TypeError:
2265 filename = make_filename(args)
2280 filename = make_filename(args)
2266 datafile = 1
2281 datafile = 1
2267 warn('Could not find file where `%s` is defined.\n'
2282 warn('Could not find file where `%s` is defined.\n'
2268 'Opening a file named `%s`' % (args,filename))
2283 'Opening a file named `%s`' % (args,filename))
2269 # Now, make sure we can actually read the source (if it was in
2284 # Now, make sure we can actually read the source (if it was in
2270 # a temp file it's gone by now).
2285 # a temp file it's gone by now).
2271 if datafile:
2286 if datafile:
2272 try:
2287 try:
2273 if lineno is None:
2288 if lineno is None:
2274 lineno = inspect.getsourcelines(data)[1]
2289 lineno = inspect.getsourcelines(data)[1]
2275 except IOError:
2290 except IOError:
2276 filename = make_filename(args)
2291 filename = make_filename(args)
2277 if filename is None:
2292 if filename is None:
2278 warn('The file `%s` where `%s` was defined cannot '
2293 warn('The file `%s` where `%s` was defined cannot '
2279 'be read.' % (filename,data))
2294 'be read.' % (filename,data))
2280 return
2295 return
2281 use_temp = 0
2296 use_temp = 0
2282 else:
2297 else:
2283 data = ''
2298 data = ''
2284
2299
2285 if use_temp:
2300 if use_temp:
2286 filename = self.shell.mktempfile(data)
2301 filename = self.shell.mktempfile(data)
2287 print 'IPython will make a temporary file named:',filename
2302 print 'IPython will make a temporary file named:',filename
2288
2303
2289 # do actual editing here
2304 # do actual editing here
2290 print 'Editing...',
2305 print 'Editing...',
2291 sys.stdout.flush()
2306 sys.stdout.flush()
2292 self.shell.hooks.editor(filename,lineno)
2307 self.shell.hooks.editor(filename,lineno)
2293 if opts.has_key('x'): # -x prevents actual execution
2308 if opts.has_key('x'): # -x prevents actual execution
2294 print
2309 print
2295 else:
2310 else:
2296 print 'done. Executing edited code...'
2311 print 'done. Executing edited code...'
2297 if opts_r:
2312 if opts_r:
2298 self.shell.runlines(file_read(filename))
2313 self.shell.runlines(file_read(filename))
2299 else:
2314 else:
2300 self.shell.safe_execfile(filename,self.shell.user_ns,
2315 self.shell.safe_execfile(filename,self.shell.user_ns,
2301 self.shell.user_ns)
2316 self.shell.user_ns)
2302 if use_temp:
2317 if use_temp:
2303 try:
2318 try:
2304 return open(filename).read()
2319 return open(filename).read()
2305 except IOError,msg:
2320 except IOError,msg:
2306 if msg.filename == filename:
2321 if msg.filename == filename:
2307 warn('File not found. Did you forget to save?')
2322 warn('File not found. Did you forget to save?')
2308 return
2323 return
2309 else:
2324 else:
2310 self.shell.showtraceback()
2325 self.shell.showtraceback()
2311
2326
2312 def magic_xmode(self,parameter_s = ''):
2327 def magic_xmode(self,parameter_s = ''):
2313 """Switch modes for the exception handlers.
2328 """Switch modes for the exception handlers.
2314
2329
2315 Valid modes: Plain, Context and Verbose.
2330 Valid modes: Plain, Context and Verbose.
2316
2331
2317 If called without arguments, acts as a toggle."""
2332 If called without arguments, acts as a toggle."""
2318
2333
2319 def xmode_switch_err(name):
2334 def xmode_switch_err(name):
2320 warn('Error changing %s exception modes.\n%s' %
2335 warn('Error changing %s exception modes.\n%s' %
2321 (name,sys.exc_info()[1]))
2336 (name,sys.exc_info()[1]))
2322
2337
2323 shell = self.shell
2338 shell = self.shell
2324 new_mode = parameter_s.strip().capitalize()
2339 new_mode = parameter_s.strip().capitalize()
2325 try:
2340 try:
2326 shell.InteractiveTB.set_mode(mode=new_mode)
2341 shell.InteractiveTB.set_mode(mode=new_mode)
2327 print 'Exception reporting mode:',shell.InteractiveTB.mode
2342 print 'Exception reporting mode:',shell.InteractiveTB.mode
2328 except:
2343 except:
2329 xmode_switch_err('user')
2344 xmode_switch_err('user')
2330
2345
2331 # threaded shells use a special handler in sys.excepthook
2346 # threaded shells use a special handler in sys.excepthook
2332 if shell.isthreaded:
2347 if shell.isthreaded:
2333 try:
2348 try:
2334 shell.sys_excepthook.set_mode(mode=new_mode)
2349 shell.sys_excepthook.set_mode(mode=new_mode)
2335 except:
2350 except:
2336 xmode_switch_err('threaded')
2351 xmode_switch_err('threaded')
2337
2352
2338 def magic_colors(self,parameter_s = ''):
2353 def magic_colors(self,parameter_s = ''):
2339 """Switch color scheme for prompts, info system and exception handlers.
2354 """Switch color scheme for prompts, info system and exception handlers.
2340
2355
2341 Currently implemented schemes: NoColor, Linux, LightBG.
2356 Currently implemented schemes: NoColor, Linux, LightBG.
2342
2357
2343 Color scheme names are not case-sensitive."""
2358 Color scheme names are not case-sensitive."""
2344
2359
2345 def color_switch_err(name):
2360 def color_switch_err(name):
2346 warn('Error changing %s color schemes.\n%s' %
2361 warn('Error changing %s color schemes.\n%s' %
2347 (name,sys.exc_info()[1]))
2362 (name,sys.exc_info()[1]))
2348
2363
2349
2364
2350 new_scheme = parameter_s.strip()
2365 new_scheme = parameter_s.strip()
2351 if not new_scheme:
2366 if not new_scheme:
2352 raise UsageError(
2367 raise UsageError(
2353 "%colors: you must specify a color scheme. See '%colors?'")
2368 "%colors: you must specify a color scheme. See '%colors?'")
2354 return
2369 return
2355 # local shortcut
2370 # local shortcut
2356 shell = self.shell
2371 shell = self.shell
2357
2372
2358 import IPython.rlineimpl as readline
2373 import IPython.rlineimpl as readline
2359
2374
2360 if not readline.have_readline and sys.platform == "win32":
2375 if not readline.have_readline and sys.platform == "win32":
2361 msg = """\
2376 msg = """\
2362 Proper color support under MS Windows requires the pyreadline library.
2377 Proper color support under MS Windows requires the pyreadline library.
2363 You can find it at:
2378 You can find it at:
2364 http://ipython.scipy.org/moin/PyReadline/Intro
2379 http://ipython.scipy.org/moin/PyReadline/Intro
2365 Gary's readline needs the ctypes module, from:
2380 Gary's readline needs the ctypes module, from:
2366 http://starship.python.net/crew/theller/ctypes
2381 http://starship.python.net/crew/theller/ctypes
2367 (Note that ctypes is already part of Python versions 2.5 and newer).
2382 (Note that ctypes is already part of Python versions 2.5 and newer).
2368
2383
2369 Defaulting color scheme to 'NoColor'"""
2384 Defaulting color scheme to 'NoColor'"""
2370 new_scheme = 'NoColor'
2385 new_scheme = 'NoColor'
2371 warn(msg)
2386 warn(msg)
2372
2387
2373 # readline option is 0
2388 # readline option is 0
2374 if not shell.has_readline:
2389 if not shell.has_readline:
2375 new_scheme = 'NoColor'
2390 new_scheme = 'NoColor'
2376
2391
2377 # Set prompt colors
2392 # Set prompt colors
2378 try:
2393 try:
2379 shell.outputcache.set_colors(new_scheme)
2394 shell.outputcache.set_colors(new_scheme)
2380 except:
2395 except:
2381 color_switch_err('prompt')
2396 color_switch_err('prompt')
2382 else:
2397 else:
2383 shell.rc.colors = \
2398 shell.rc.colors = \
2384 shell.outputcache.color_table.active_scheme_name
2399 shell.outputcache.color_table.active_scheme_name
2385 # Set exception colors
2400 # Set exception colors
2386 try:
2401 try:
2387 shell.InteractiveTB.set_colors(scheme = new_scheme)
2402 shell.InteractiveTB.set_colors(scheme = new_scheme)
2388 shell.SyntaxTB.set_colors(scheme = new_scheme)
2403 shell.SyntaxTB.set_colors(scheme = new_scheme)
2389 except:
2404 except:
2390 color_switch_err('exception')
2405 color_switch_err('exception')
2391
2406
2392 # threaded shells use a verbose traceback in sys.excepthook
2407 # threaded shells use a verbose traceback in sys.excepthook
2393 if shell.isthreaded:
2408 if shell.isthreaded:
2394 try:
2409 try:
2395 shell.sys_excepthook.set_colors(scheme=new_scheme)
2410 shell.sys_excepthook.set_colors(scheme=new_scheme)
2396 except:
2411 except:
2397 color_switch_err('system exception handler')
2412 color_switch_err('system exception handler')
2398
2413
2399 # Set info (for 'object?') colors
2414 # Set info (for 'object?') colors
2400 if shell.rc.color_info:
2415 if shell.rc.color_info:
2401 try:
2416 try:
2402 shell.inspector.set_active_scheme(new_scheme)
2417 shell.inspector.set_active_scheme(new_scheme)
2403 except:
2418 except:
2404 color_switch_err('object inspector')
2419 color_switch_err('object inspector')
2405 else:
2420 else:
2406 shell.inspector.set_active_scheme('NoColor')
2421 shell.inspector.set_active_scheme('NoColor')
2407
2422
2408 def magic_color_info(self,parameter_s = ''):
2423 def magic_color_info(self,parameter_s = ''):
2409 """Toggle color_info.
2424 """Toggle color_info.
2410
2425
2411 The color_info configuration parameter controls whether colors are
2426 The color_info configuration parameter controls whether colors are
2412 used for displaying object details (by things like %psource, %pfile or
2427 used for displaying object details (by things like %psource, %pfile or
2413 the '?' system). This function toggles this value with each call.
2428 the '?' system). This function toggles this value with each call.
2414
2429
2415 Note that unless you have a fairly recent pager (less works better
2430 Note that unless you have a fairly recent pager (less works better
2416 than more) in your system, using colored object information displays
2431 than more) in your system, using colored object information displays
2417 will not work properly. Test it and see."""
2432 will not work properly. Test it and see."""
2418
2433
2419 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2434 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2420 self.magic_colors(self.shell.rc.colors)
2435 self.magic_colors(self.shell.rc.colors)
2421 print 'Object introspection functions have now coloring:',
2436 print 'Object introspection functions have now coloring:',
2422 print ['OFF','ON'][self.shell.rc.color_info]
2437 print ['OFF','ON'][self.shell.rc.color_info]
2423
2438
2424 def magic_Pprint(self, parameter_s=''):
2439 def magic_Pprint(self, parameter_s=''):
2425 """Toggle pretty printing on/off."""
2440 """Toggle pretty printing on/off."""
2426
2441
2427 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2442 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2428 print 'Pretty printing has been turned', \
2443 print 'Pretty printing has been turned', \
2429 ['OFF','ON'][self.shell.rc.pprint]
2444 ['OFF','ON'][self.shell.rc.pprint]
2430
2445
2431 def magic_exit(self, parameter_s=''):
2446 def magic_exit(self, parameter_s=''):
2432 """Exit IPython, confirming if configured to do so.
2447 """Exit IPython, confirming if configured to do so.
2433
2448
2434 You can configure whether IPython asks for confirmation upon exit by
2449 You can configure whether IPython asks for confirmation upon exit by
2435 setting the confirm_exit flag in the ipythonrc file."""
2450 setting the confirm_exit flag in the ipythonrc file."""
2436
2451
2437 self.shell.exit()
2452 self.shell.exit()
2438
2453
2439 def magic_quit(self, parameter_s=''):
2454 def magic_quit(self, parameter_s=''):
2440 """Exit IPython, confirming if configured to do so (like %exit)"""
2455 """Exit IPython, confirming if configured to do so (like %exit)"""
2441
2456
2442 self.shell.exit()
2457 self.shell.exit()
2443
2458
2444 def magic_Exit(self, parameter_s=''):
2459 def magic_Exit(self, parameter_s=''):
2445 """Exit IPython without confirmation."""
2460 """Exit IPython without confirmation."""
2446
2461
2447 self.shell.exit_now = True
2462 self.shell.exit_now = True
2448
2463
2449 #......................................................................
2464 #......................................................................
2450 # Functions to implement unix shell-type things
2465 # Functions to implement unix shell-type things
2451
2466
2452 def magic_alias(self, parameter_s = ''):
2467 def magic_alias(self, parameter_s = ''):
2453 """Define an alias for a system command.
2468 """Define an alias for a system command.
2454
2469
2455 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2470 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2456
2471
2457 Then, typing 'alias_name params' will execute the system command 'cmd
2472 Then, typing 'alias_name params' will execute the system command 'cmd
2458 params' (from your underlying operating system).
2473 params' (from your underlying operating system).
2459
2474
2460 Aliases have lower precedence than magic functions and Python normal
2475 Aliases have lower precedence than magic functions and Python normal
2461 variables, so if 'foo' is both a Python variable and an alias, the
2476 variables, so if 'foo' is both a Python variable and an alias, the
2462 alias can not be executed until 'del foo' removes the Python variable.
2477 alias can not be executed until 'del foo' removes the Python variable.
2463
2478
2464 You can use the %l specifier in an alias definition to represent the
2479 You can use the %l specifier in an alias definition to represent the
2465 whole line when the alias is called. For example:
2480 whole line when the alias is called. For example:
2466
2481
2467 In [2]: alias all echo "Input in brackets: <%l>"\\
2482 In [2]: alias all echo "Input in brackets: <%l>"\\
2468 In [3]: all hello world\\
2483 In [3]: all hello world\\
2469 Input in brackets: <hello world>
2484 Input in brackets: <hello world>
2470
2485
2471 You can also define aliases with parameters using %s specifiers (one
2486 You can also define aliases with parameters using %s specifiers (one
2472 per parameter):
2487 per parameter):
2473
2488
2474 In [1]: alias parts echo first %s second %s\\
2489 In [1]: alias parts echo first %s second %s\\
2475 In [2]: %parts A B\\
2490 In [2]: %parts A B\\
2476 first A second B\\
2491 first A second B\\
2477 In [3]: %parts A\\
2492 In [3]: %parts A\\
2478 Incorrect number of arguments: 2 expected.\\
2493 Incorrect number of arguments: 2 expected.\\
2479 parts is an alias to: 'echo first %s second %s'
2494 parts is an alias to: 'echo first %s second %s'
2480
2495
2481 Note that %l and %s are mutually exclusive. You can only use one or
2496 Note that %l and %s are mutually exclusive. You can only use one or
2482 the other in your aliases.
2497 the other in your aliases.
2483
2498
2484 Aliases expand Python variables just like system calls using ! or !!
2499 Aliases expand Python variables just like system calls using ! or !!
2485 do: all expressions prefixed with '$' get expanded. For details of
2500 do: all expressions prefixed with '$' get expanded. For details of
2486 the semantic rules, see PEP-215:
2501 the semantic rules, see PEP-215:
2487 http://www.python.org/peps/pep-0215.html. This is the library used by
2502 http://www.python.org/peps/pep-0215.html. This is the library used by
2488 IPython for variable expansion. If you want to access a true shell
2503 IPython for variable expansion. If you want to access a true shell
2489 variable, an extra $ is necessary to prevent its expansion by IPython:
2504 variable, an extra $ is necessary to prevent its expansion by IPython:
2490
2505
2491 In [6]: alias show echo\\
2506 In [6]: alias show echo\\
2492 In [7]: PATH='A Python string'\\
2507 In [7]: PATH='A Python string'\\
2493 In [8]: show $PATH\\
2508 In [8]: show $PATH\\
2494 A Python string\\
2509 A Python string\\
2495 In [9]: show $$PATH\\
2510 In [9]: show $$PATH\\
2496 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2511 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2497
2512
2498 You can use the alias facility to acess all of $PATH. See the %rehash
2513 You can use the alias facility to acess all of $PATH. See the %rehash
2499 and %rehashx functions, which automatically create aliases for the
2514 and %rehashx functions, which automatically create aliases for the
2500 contents of your $PATH.
2515 contents of your $PATH.
2501
2516
2502 If called with no parameters, %alias prints the current alias table."""
2517 If called with no parameters, %alias prints the current alias table."""
2503
2518
2504 par = parameter_s.strip()
2519 par = parameter_s.strip()
2505 if not par:
2520 if not par:
2506 stored = self.db.get('stored_aliases', {} )
2521 stored = self.db.get('stored_aliases', {} )
2507 atab = self.shell.alias_table
2522 atab = self.shell.alias_table
2508 aliases = atab.keys()
2523 aliases = atab.keys()
2509 aliases.sort()
2524 aliases.sort()
2510 res = []
2525 res = []
2511 showlast = []
2526 showlast = []
2512 for alias in aliases:
2527 for alias in aliases:
2513 special = False
2528 special = False
2514 try:
2529 try:
2515 tgt = atab[alias][1]
2530 tgt = atab[alias][1]
2516 except (TypeError, AttributeError):
2531 except (TypeError, AttributeError):
2517 # unsubscriptable? probably a callable
2532 # unsubscriptable? probably a callable
2518 tgt = atab[alias]
2533 tgt = atab[alias]
2519 special = True
2534 special = True
2520 # 'interesting' aliases
2535 # 'interesting' aliases
2521 if (alias in stored or
2536 if (alias in stored or
2522 special or
2537 special or
2523 alias.lower() != os.path.splitext(tgt)[0].lower() or
2538 alias.lower() != os.path.splitext(tgt)[0].lower() or
2524 ' ' in tgt):
2539 ' ' in tgt):
2525 showlast.append((alias, tgt))
2540 showlast.append((alias, tgt))
2526 else:
2541 else:
2527 res.append((alias, tgt ))
2542 res.append((alias, tgt ))
2528
2543
2529 # show most interesting aliases last
2544 # show most interesting aliases last
2530 res.extend(showlast)
2545 res.extend(showlast)
2531 print "Total number of aliases:",len(aliases)
2546 print "Total number of aliases:",len(aliases)
2532 return res
2547 return res
2533 try:
2548 try:
2534 alias,cmd = par.split(None,1)
2549 alias,cmd = par.split(None,1)
2535 except:
2550 except:
2536 print OInspect.getdoc(self.magic_alias)
2551 print OInspect.getdoc(self.magic_alias)
2537 else:
2552 else:
2538 nargs = cmd.count('%s')
2553 nargs = cmd.count('%s')
2539 if nargs>0 and cmd.find('%l')>=0:
2554 if nargs>0 and cmd.find('%l')>=0:
2540 error('The %s and %l specifiers are mutually exclusive '
2555 error('The %s and %l specifiers are mutually exclusive '
2541 'in alias definitions.')
2556 'in alias definitions.')
2542 else: # all looks OK
2557 else: # all looks OK
2543 self.shell.alias_table[alias] = (nargs,cmd)
2558 self.shell.alias_table[alias] = (nargs,cmd)
2544 self.shell.alias_table_validate(verbose=0)
2559 self.shell.alias_table_validate(verbose=0)
2545 # end magic_alias
2560 # end magic_alias
2546
2561
2547 def magic_unalias(self, parameter_s = ''):
2562 def magic_unalias(self, parameter_s = ''):
2548 """Remove an alias"""
2563 """Remove an alias"""
2549
2564
2550 aname = parameter_s.strip()
2565 aname = parameter_s.strip()
2551 if aname in self.shell.alias_table:
2566 if aname in self.shell.alias_table:
2552 del self.shell.alias_table[aname]
2567 del self.shell.alias_table[aname]
2553 stored = self.db.get('stored_aliases', {} )
2568 stored = self.db.get('stored_aliases', {} )
2554 if aname in stored:
2569 if aname in stored:
2555 print "Removing %stored alias",aname
2570 print "Removing %stored alias",aname
2556 del stored[aname]
2571 del stored[aname]
2557 self.db['stored_aliases'] = stored
2572 self.db['stored_aliases'] = stored
2558
2573
2559
2574
2560 def magic_rehashx(self, parameter_s = ''):
2575 def magic_rehashx(self, parameter_s = ''):
2561 """Update the alias table with all executable files in $PATH.
2576 """Update the alias table with all executable files in $PATH.
2562
2577
2563 This version explicitly checks that every entry in $PATH is a file
2578 This version explicitly checks that every entry in $PATH is a file
2564 with execute access (os.X_OK), so it is much slower than %rehash.
2579 with execute access (os.X_OK), so it is much slower than %rehash.
2565
2580
2566 Under Windows, it checks executability as a match agains a
2581 Under Windows, it checks executability as a match agains a
2567 '|'-separated string of extensions, stored in the IPython config
2582 '|'-separated string of extensions, stored in the IPython config
2568 variable win_exec_ext. This defaults to 'exe|com|bat'.
2583 variable win_exec_ext. This defaults to 'exe|com|bat'.
2569
2584
2570 This function also resets the root module cache of module completer,
2585 This function also resets the root module cache of module completer,
2571 used on slow filesystems.
2586 used on slow filesystems.
2572 """
2587 """
2573
2588
2574
2589
2575 ip = self.api
2590 ip = self.api
2576
2591
2577 # for the benefit of module completer in ipy_completers.py
2592 # for the benefit of module completer in ipy_completers.py
2578 del ip.db['rootmodules']
2593 del ip.db['rootmodules']
2579
2594
2580 path = [os.path.abspath(os.path.expanduser(p)) for p in
2595 path = [os.path.abspath(os.path.expanduser(p)) for p in
2581 os.environ.get('PATH','').split(os.pathsep)]
2596 os.environ.get('PATH','').split(os.pathsep)]
2582 path = filter(os.path.isdir,path)
2597 path = filter(os.path.isdir,path)
2583
2598
2584 alias_table = self.shell.alias_table
2599 alias_table = self.shell.alias_table
2585 syscmdlist = []
2600 syscmdlist = []
2586 if os.name == 'posix':
2601 if os.name == 'posix':
2587 isexec = lambda fname:os.path.isfile(fname) and \
2602 isexec = lambda fname:os.path.isfile(fname) and \
2588 os.access(fname,os.X_OK)
2603 os.access(fname,os.X_OK)
2589 else:
2604 else:
2590
2605
2591 try:
2606 try:
2592 winext = os.environ['pathext'].replace(';','|').replace('.','')
2607 winext = os.environ['pathext'].replace(';','|').replace('.','')
2593 except KeyError:
2608 except KeyError:
2594 winext = 'exe|com|bat|py'
2609 winext = 'exe|com|bat|py'
2595 if 'py' not in winext:
2610 if 'py' not in winext:
2596 winext += '|py'
2611 winext += '|py'
2597 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2612 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2598 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2613 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2599 savedir = os.getcwd()
2614 savedir = os.getcwd()
2600 try:
2615 try:
2601 # write the whole loop for posix/Windows so we don't have an if in
2616 # write the whole loop for posix/Windows so we don't have an if in
2602 # the innermost part
2617 # the innermost part
2603 if os.name == 'posix':
2618 if os.name == 'posix':
2604 for pdir in path:
2619 for pdir in path:
2605 os.chdir(pdir)
2620 os.chdir(pdir)
2606 for ff in os.listdir(pdir):
2621 for ff in os.listdir(pdir):
2607 if isexec(ff) and ff not in self.shell.no_alias:
2622 if isexec(ff) and ff not in self.shell.no_alias:
2608 # each entry in the alias table must be (N,name),
2623 # each entry in the alias table must be (N,name),
2609 # where N is the number of positional arguments of the
2624 # where N is the number of positional arguments of the
2610 # alias.
2625 # alias.
2611 alias_table[ff] = (0,ff)
2626 alias_table[ff] = (0,ff)
2612 syscmdlist.append(ff)
2627 syscmdlist.append(ff)
2613 else:
2628 else:
2614 for pdir in path:
2629 for pdir in path:
2615 os.chdir(pdir)
2630 os.chdir(pdir)
2616 for ff in os.listdir(pdir):
2631 for ff in os.listdir(pdir):
2617 base, ext = os.path.splitext(ff)
2632 base, ext = os.path.splitext(ff)
2618 if isexec(ff) and base.lower() not in self.shell.no_alias:
2633 if isexec(ff) and base.lower() not in self.shell.no_alias:
2619 if ext.lower() == '.exe':
2634 if ext.lower() == '.exe':
2620 ff = base
2635 ff = base
2621 alias_table[base.lower()] = (0,ff)
2636 alias_table[base.lower()] = (0,ff)
2622 syscmdlist.append(ff)
2637 syscmdlist.append(ff)
2623 # Make sure the alias table doesn't contain keywords or builtins
2638 # Make sure the alias table doesn't contain keywords or builtins
2624 self.shell.alias_table_validate()
2639 self.shell.alias_table_validate()
2625 # Call again init_auto_alias() so we get 'rm -i' and other
2640 # Call again init_auto_alias() so we get 'rm -i' and other
2626 # modified aliases since %rehashx will probably clobber them
2641 # modified aliases since %rehashx will probably clobber them
2627
2642
2628 # no, we don't want them. if %rehashx clobbers them, good,
2643 # no, we don't want them. if %rehashx clobbers them, good,
2629 # we'll probably get better versions
2644 # we'll probably get better versions
2630 # self.shell.init_auto_alias()
2645 # self.shell.init_auto_alias()
2631 db = ip.db
2646 db = ip.db
2632 db['syscmdlist'] = syscmdlist
2647 db['syscmdlist'] = syscmdlist
2633 finally:
2648 finally:
2634 os.chdir(savedir)
2649 os.chdir(savedir)
2635
2650
2636 def magic_pwd(self, parameter_s = ''):
2651 def magic_pwd(self, parameter_s = ''):
2637 """Return the current working directory path."""
2652 """Return the current working directory path."""
2638 return os.getcwd()
2653 return os.getcwd()
2639
2654
2640 def magic_cd(self, parameter_s=''):
2655 def magic_cd(self, parameter_s=''):
2641 """Change the current working directory.
2656 """Change the current working directory.
2642
2657
2643 This command automatically maintains an internal list of directories
2658 This command automatically maintains an internal list of directories
2644 you visit during your IPython session, in the variable _dh. The
2659 you visit during your IPython session, in the variable _dh. The
2645 command %dhist shows this history nicely formatted. You can also
2660 command %dhist shows this history nicely formatted. You can also
2646 do 'cd -<tab>' to see directory history conveniently.
2661 do 'cd -<tab>' to see directory history conveniently.
2647
2662
2648 Usage:
2663 Usage:
2649
2664
2650 cd 'dir': changes to directory 'dir'.
2665 cd 'dir': changes to directory 'dir'.
2651
2666
2652 cd -: changes to the last visited directory.
2667 cd -: changes to the last visited directory.
2653
2668
2654 cd -<n>: changes to the n-th directory in the directory history.
2669 cd -<n>: changes to the n-th directory in the directory history.
2655
2670
2656 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2671 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2657 (note: cd <bookmark_name> is enough if there is no
2672 (note: cd <bookmark_name> is enough if there is no
2658 directory <bookmark_name>, but a bookmark with the name exists.)
2673 directory <bookmark_name>, but a bookmark with the name exists.)
2659 'cd -b <tab>' allows you to tab-complete bookmark names.
2674 'cd -b <tab>' allows you to tab-complete bookmark names.
2660
2675
2661 Options:
2676 Options:
2662
2677
2663 -q: quiet. Do not print the working directory after the cd command is
2678 -q: quiet. Do not print the working directory after the cd command is
2664 executed. By default IPython's cd command does print this directory,
2679 executed. By default IPython's cd command does print this directory,
2665 since the default prompts do not display path information.
2680 since the default prompts do not display path information.
2666
2681
2667 Note that !cd doesn't work for this purpose because the shell where
2682 Note that !cd doesn't work for this purpose because the shell where
2668 !command runs is immediately discarded after executing 'command'."""
2683 !command runs is immediately discarded after executing 'command'."""
2669
2684
2670 parameter_s = parameter_s.strip()
2685 parameter_s = parameter_s.strip()
2671 #bkms = self.shell.persist.get("bookmarks",{})
2686 #bkms = self.shell.persist.get("bookmarks",{})
2672
2687
2673 oldcwd = os.getcwd()
2688 oldcwd = os.getcwd()
2674 numcd = re.match(r'(-)(\d+)$',parameter_s)
2689 numcd = re.match(r'(-)(\d+)$',parameter_s)
2675 # jump in directory history by number
2690 # jump in directory history by number
2676 if numcd:
2691 if numcd:
2677 nn = int(numcd.group(2))
2692 nn = int(numcd.group(2))
2678 try:
2693 try:
2679 ps = self.shell.user_ns['_dh'][nn]
2694 ps = self.shell.user_ns['_dh'][nn]
2680 except IndexError:
2695 except IndexError:
2681 print 'The requested directory does not exist in history.'
2696 print 'The requested directory does not exist in history.'
2682 return
2697 return
2683 else:
2698 else:
2684 opts = {}
2699 opts = {}
2685 else:
2700 else:
2686 #turn all non-space-escaping backslashes to slashes,
2701 #turn all non-space-escaping backslashes to slashes,
2687 # for c:\windows\directory\names\
2702 # for c:\windows\directory\names\
2688 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2703 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2689 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2704 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2690 # jump to previous
2705 # jump to previous
2691 if ps == '-':
2706 if ps == '-':
2692 try:
2707 try:
2693 ps = self.shell.user_ns['_dh'][-2]
2708 ps = self.shell.user_ns['_dh'][-2]
2694 except IndexError:
2709 except IndexError:
2695 raise UsageError('%cd -: No previous directory to change to.')
2710 raise UsageError('%cd -: No previous directory to change to.')
2696 # jump to bookmark if needed
2711 # jump to bookmark if needed
2697 else:
2712 else:
2698 if not os.path.isdir(ps) or opts.has_key('b'):
2713 if not os.path.isdir(ps) or opts.has_key('b'):
2699 bkms = self.db.get('bookmarks', {})
2714 bkms = self.db.get('bookmarks', {})
2700
2715
2701 if bkms.has_key(ps):
2716 if bkms.has_key(ps):
2702 target = bkms[ps]
2717 target = bkms[ps]
2703 print '(bookmark:%s) -> %s' % (ps,target)
2718 print '(bookmark:%s) -> %s' % (ps,target)
2704 ps = target
2719 ps = target
2705 else:
2720 else:
2706 if opts.has_key('b'):
2721 if opts.has_key('b'):
2707 raise UsageError("Bookmark '%s' not found. "
2722 raise UsageError("Bookmark '%s' not found. "
2708 "Use '%%bookmark -l' to see your bookmarks." % ps)
2723 "Use '%%bookmark -l' to see your bookmarks." % ps)
2709
2724
2710 # at this point ps should point to the target dir
2725 # at this point ps should point to the target dir
2711 if ps:
2726 if ps:
2712 try:
2727 try:
2713 os.chdir(os.path.expanduser(ps))
2728 os.chdir(os.path.expanduser(ps))
2714 if self.shell.rc.term_title:
2729 if self.shell.rc.term_title:
2715 #print 'set term title:',self.shell.rc.term_title # dbg
2730 #print 'set term title:',self.shell.rc.term_title # dbg
2716 ttitle = 'IPy ' + abbrev_cwd()
2731 ttitle = 'IPy ' + abbrev_cwd()
2717 platutils.set_term_title(ttitle)
2732 platutils.set_term_title(ttitle)
2718 except OSError:
2733 except OSError:
2719 print sys.exc_info()[1]
2734 print sys.exc_info()[1]
2720 else:
2735 else:
2721 cwd = os.getcwd()
2736 cwd = os.getcwd()
2722 dhist = self.shell.user_ns['_dh']
2737 dhist = self.shell.user_ns['_dh']
2723 if oldcwd != cwd:
2738 if oldcwd != cwd:
2724 dhist.append(cwd)
2739 dhist.append(cwd)
2725 self.db['dhist'] = compress_dhist(dhist)[-100:]
2740 self.db['dhist'] = compress_dhist(dhist)[-100:]
2726
2741
2727 else:
2742 else:
2728 os.chdir(self.shell.home_dir)
2743 os.chdir(self.shell.home_dir)
2729 if self.shell.rc.term_title:
2744 if self.shell.rc.term_title:
2730 platutils.set_term_title("IPy ~")
2745 platutils.set_term_title("IPy ~")
2731 cwd = os.getcwd()
2746 cwd = os.getcwd()
2732 dhist = self.shell.user_ns['_dh']
2747 dhist = self.shell.user_ns['_dh']
2733
2748
2734 if oldcwd != cwd:
2749 if oldcwd != cwd:
2735 dhist.append(cwd)
2750 dhist.append(cwd)
2736 self.db['dhist'] = compress_dhist(dhist)[-100:]
2751 self.db['dhist'] = compress_dhist(dhist)[-100:]
2737 if not 'q' in opts and self.shell.user_ns['_dh']:
2752 if not 'q' in opts and self.shell.user_ns['_dh']:
2738 print self.shell.user_ns['_dh'][-1]
2753 print self.shell.user_ns['_dh'][-1]
2739
2754
2740
2755
2741 def magic_env(self, parameter_s=''):
2756 def magic_env(self, parameter_s=''):
2742 """List environment variables."""
2757 """List environment variables."""
2743
2758
2744 return os.environ.data
2759 return os.environ.data
2745
2760
2746 def magic_pushd(self, parameter_s=''):
2761 def magic_pushd(self, parameter_s=''):
2747 """Place the current dir on stack and change directory.
2762 """Place the current dir on stack and change directory.
2748
2763
2749 Usage:\\
2764 Usage:\\
2750 %pushd ['dirname']
2765 %pushd ['dirname']
2751 """
2766 """
2752
2767
2753 dir_s = self.shell.dir_stack
2768 dir_s = self.shell.dir_stack
2754 tgt = os.path.expanduser(parameter_s)
2769 tgt = os.path.expanduser(parameter_s)
2755 cwd = os.getcwd().replace(self.home_dir,'~')
2770 cwd = os.getcwd().replace(self.home_dir,'~')
2756 if tgt:
2771 if tgt:
2757 self.magic_cd(parameter_s)
2772 self.magic_cd(parameter_s)
2758 dir_s.insert(0,cwd)
2773 dir_s.insert(0,cwd)
2759 return self.magic_dirs()
2774 return self.magic_dirs()
2760
2775
2761 def magic_popd(self, parameter_s=''):
2776 def magic_popd(self, parameter_s=''):
2762 """Change to directory popped off the top of the stack.
2777 """Change to directory popped off the top of the stack.
2763 """
2778 """
2764 if not self.shell.dir_stack:
2779 if not self.shell.dir_stack:
2765 raise UsageError("%popd on empty stack")
2780 raise UsageError("%popd on empty stack")
2766 top = self.shell.dir_stack.pop(0)
2781 top = self.shell.dir_stack.pop(0)
2767 self.magic_cd(top)
2782 self.magic_cd(top)
2768 print "popd ->",top
2783 print "popd ->",top
2769
2784
2770 def magic_dirs(self, parameter_s=''):
2785 def magic_dirs(self, parameter_s=''):
2771 """Return the current directory stack."""
2786 """Return the current directory stack."""
2772
2787
2773 return self.shell.dir_stack
2788 return self.shell.dir_stack
2774
2789
2775 def magic_dhist(self, parameter_s=''):
2790 def magic_dhist(self, parameter_s=''):
2776 """Print your history of visited directories.
2791 """Print your history of visited directories.
2777
2792
2778 %dhist -> print full history\\
2793 %dhist -> print full history\\
2779 %dhist n -> print last n entries only\\
2794 %dhist n -> print last n entries only\\
2780 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2795 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2781
2796
2782 This history is automatically maintained by the %cd command, and
2797 This history is automatically maintained by the %cd command, and
2783 always available as the global list variable _dh. You can use %cd -<n>
2798 always available as the global list variable _dh. You can use %cd -<n>
2784 to go to directory number <n>.
2799 to go to directory number <n>.
2785
2800
2786 Note that most of time, you should view directory history by entering
2801 Note that most of time, you should view directory history by entering
2787 cd -<TAB>.
2802 cd -<TAB>.
2788
2803
2789 """
2804 """
2790
2805
2791 dh = self.shell.user_ns['_dh']
2806 dh = self.shell.user_ns['_dh']
2792 if parameter_s:
2807 if parameter_s:
2793 try:
2808 try:
2794 args = map(int,parameter_s.split())
2809 args = map(int,parameter_s.split())
2795 except:
2810 except:
2796 self.arg_err(Magic.magic_dhist)
2811 self.arg_err(Magic.magic_dhist)
2797 return
2812 return
2798 if len(args) == 1:
2813 if len(args) == 1:
2799 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2814 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2800 elif len(args) == 2:
2815 elif len(args) == 2:
2801 ini,fin = args
2816 ini,fin = args
2802 else:
2817 else:
2803 self.arg_err(Magic.magic_dhist)
2818 self.arg_err(Magic.magic_dhist)
2804 return
2819 return
2805 else:
2820 else:
2806 ini,fin = 0,len(dh)
2821 ini,fin = 0,len(dh)
2807 nlprint(dh,
2822 nlprint(dh,
2808 header = 'Directory history (kept in _dh)',
2823 header = 'Directory history (kept in _dh)',
2809 start=ini,stop=fin)
2824 start=ini,stop=fin)
2810
2825
2811
2826
2812 def magic_sc(self, parameter_s=''):
2827 def magic_sc(self, parameter_s=''):
2813 """Shell capture - execute a shell command and capture its output.
2828 """Shell capture - execute a shell command and capture its output.
2814
2829
2815 DEPRECATED. Suboptimal, retained for backwards compatibility.
2830 DEPRECATED. Suboptimal, retained for backwards compatibility.
2816
2831
2817 You should use the form 'var = !command' instead. Example:
2832 You should use the form 'var = !command' instead. Example:
2818
2833
2819 "%sc -l myfiles = ls ~" should now be written as
2834 "%sc -l myfiles = ls ~" should now be written as
2820
2835
2821 "myfiles = !ls ~"
2836 "myfiles = !ls ~"
2822
2837
2823 myfiles.s, myfiles.l and myfiles.n still apply as documented
2838 myfiles.s, myfiles.l and myfiles.n still apply as documented
2824 below.
2839 below.
2825
2840
2826 --
2841 --
2827 %sc [options] varname=command
2842 %sc [options] varname=command
2828
2843
2829 IPython will run the given command using commands.getoutput(), and
2844 IPython will run the given command using commands.getoutput(), and
2830 will then update the user's interactive namespace with a variable
2845 will then update the user's interactive namespace with a variable
2831 called varname, containing the value of the call. Your command can
2846 called varname, containing the value of the call. Your command can
2832 contain shell wildcards, pipes, etc.
2847 contain shell wildcards, pipes, etc.
2833
2848
2834 The '=' sign in the syntax is mandatory, and the variable name you
2849 The '=' sign in the syntax is mandatory, and the variable name you
2835 supply must follow Python's standard conventions for valid names.
2850 supply must follow Python's standard conventions for valid names.
2836
2851
2837 (A special format without variable name exists for internal use)
2852 (A special format without variable name exists for internal use)
2838
2853
2839 Options:
2854 Options:
2840
2855
2841 -l: list output. Split the output on newlines into a list before
2856 -l: list output. Split the output on newlines into a list before
2842 assigning it to the given variable. By default the output is stored
2857 assigning it to the given variable. By default the output is stored
2843 as a single string.
2858 as a single string.
2844
2859
2845 -v: verbose. Print the contents of the variable.
2860 -v: verbose. Print the contents of the variable.
2846
2861
2847 In most cases you should not need to split as a list, because the
2862 In most cases you should not need to split as a list, because the
2848 returned value is a special type of string which can automatically
2863 returned value is a special type of string which can automatically
2849 provide its contents either as a list (split on newlines) or as a
2864 provide its contents either as a list (split on newlines) or as a
2850 space-separated string. These are convenient, respectively, either
2865 space-separated string. These are convenient, respectively, either
2851 for sequential processing or to be passed to a shell command.
2866 for sequential processing or to be passed to a shell command.
2852
2867
2853 For example:
2868 For example:
2854
2869
2855 # Capture into variable a
2870 # Capture into variable a
2856 In [9]: sc a=ls *py
2871 In [9]: sc a=ls *py
2857
2872
2858 # a is a string with embedded newlines
2873 # a is a string with embedded newlines
2859 In [10]: a
2874 In [10]: a
2860 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2875 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2861
2876
2862 # which can be seen as a list:
2877 # which can be seen as a list:
2863 In [11]: a.l
2878 In [11]: a.l
2864 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2879 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2865
2880
2866 # or as a whitespace-separated string:
2881 # or as a whitespace-separated string:
2867 In [12]: a.s
2882 In [12]: a.s
2868 Out[12]: 'setup.py win32_manual_post_install.py'
2883 Out[12]: 'setup.py win32_manual_post_install.py'
2869
2884
2870 # a.s is useful to pass as a single command line:
2885 # a.s is useful to pass as a single command line:
2871 In [13]: !wc -l $a.s
2886 In [13]: !wc -l $a.s
2872 146 setup.py
2887 146 setup.py
2873 130 win32_manual_post_install.py
2888 130 win32_manual_post_install.py
2874 276 total
2889 276 total
2875
2890
2876 # while the list form is useful to loop over:
2891 # while the list form is useful to loop over:
2877 In [14]: for f in a.l:
2892 In [14]: for f in a.l:
2878 ....: !wc -l $f
2893 ....: !wc -l $f
2879 ....:
2894 ....:
2880 146 setup.py
2895 146 setup.py
2881 130 win32_manual_post_install.py
2896 130 win32_manual_post_install.py
2882
2897
2883 Similiarly, the lists returned by the -l option are also special, in
2898 Similiarly, the lists returned by the -l option are also special, in
2884 the sense that you can equally invoke the .s attribute on them to
2899 the sense that you can equally invoke the .s attribute on them to
2885 automatically get a whitespace-separated string from their contents:
2900 automatically get a whitespace-separated string from their contents:
2886
2901
2887 In [1]: sc -l b=ls *py
2902 In [1]: sc -l b=ls *py
2888
2903
2889 In [2]: b
2904 In [2]: b
2890 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2905 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2891
2906
2892 In [3]: b.s
2907 In [3]: b.s
2893 Out[3]: 'setup.py win32_manual_post_install.py'
2908 Out[3]: 'setup.py win32_manual_post_install.py'
2894
2909
2895 In summary, both the lists and strings used for ouptut capture have
2910 In summary, both the lists and strings used for ouptut capture have
2896 the following special attributes:
2911 the following special attributes:
2897
2912
2898 .l (or .list) : value as list.
2913 .l (or .list) : value as list.
2899 .n (or .nlstr): value as newline-separated string.
2914 .n (or .nlstr): value as newline-separated string.
2900 .s (or .spstr): value as space-separated string.
2915 .s (or .spstr): value as space-separated string.
2901 """
2916 """
2902
2917
2903 opts,args = self.parse_options(parameter_s,'lv')
2918 opts,args = self.parse_options(parameter_s,'lv')
2904 # Try to get a variable name and command to run
2919 # Try to get a variable name and command to run
2905 try:
2920 try:
2906 # the variable name must be obtained from the parse_options
2921 # the variable name must be obtained from the parse_options
2907 # output, which uses shlex.split to strip options out.
2922 # output, which uses shlex.split to strip options out.
2908 var,_ = args.split('=',1)
2923 var,_ = args.split('=',1)
2909 var = var.strip()
2924 var = var.strip()
2910 # But the the command has to be extracted from the original input
2925 # But the the command has to be extracted from the original input
2911 # parameter_s, not on what parse_options returns, to avoid the
2926 # parameter_s, not on what parse_options returns, to avoid the
2912 # quote stripping which shlex.split performs on it.
2927 # quote stripping which shlex.split performs on it.
2913 _,cmd = parameter_s.split('=',1)
2928 _,cmd = parameter_s.split('=',1)
2914 except ValueError:
2929 except ValueError:
2915 var,cmd = '',''
2930 var,cmd = '',''
2916 # If all looks ok, proceed
2931 # If all looks ok, proceed
2917 out,err = self.shell.getoutputerror(cmd)
2932 out,err = self.shell.getoutputerror(cmd)
2918 if err:
2933 if err:
2919 print >> Term.cerr,err
2934 print >> Term.cerr,err
2920 if opts.has_key('l'):
2935 if opts.has_key('l'):
2921 out = SList(out.split('\n'))
2936 out = SList(out.split('\n'))
2922 else:
2937 else:
2923 out = LSString(out)
2938 out = LSString(out)
2924 if opts.has_key('v'):
2939 if opts.has_key('v'):
2925 print '%s ==\n%s' % (var,pformat(out))
2940 print '%s ==\n%s' % (var,pformat(out))
2926 if var:
2941 if var:
2927 self.shell.user_ns.update({var:out})
2942 self.shell.user_ns.update({var:out})
2928 else:
2943 else:
2929 return out
2944 return out
2930
2945
2931 def magic_sx(self, parameter_s=''):
2946 def magic_sx(self, parameter_s=''):
2932 """Shell execute - run a shell command and capture its output.
2947 """Shell execute - run a shell command and capture its output.
2933
2948
2934 %sx command
2949 %sx command
2935
2950
2936 IPython will run the given command using commands.getoutput(), and
2951 IPython will run the given command using commands.getoutput(), and
2937 return the result formatted as a list (split on '\\n'). Since the
2952 return the result formatted as a list (split on '\\n'). Since the
2938 output is _returned_, it will be stored in ipython's regular output
2953 output is _returned_, it will be stored in ipython's regular output
2939 cache Out[N] and in the '_N' automatic variables.
2954 cache Out[N] and in the '_N' automatic variables.
2940
2955
2941 Notes:
2956 Notes:
2942
2957
2943 1) If an input line begins with '!!', then %sx is automatically
2958 1) If an input line begins with '!!', then %sx is automatically
2944 invoked. That is, while:
2959 invoked. That is, while:
2945 !ls
2960 !ls
2946 causes ipython to simply issue system('ls'), typing
2961 causes ipython to simply issue system('ls'), typing
2947 !!ls
2962 !!ls
2948 is a shorthand equivalent to:
2963 is a shorthand equivalent to:
2949 %sx ls
2964 %sx ls
2950
2965
2951 2) %sx differs from %sc in that %sx automatically splits into a list,
2966 2) %sx differs from %sc in that %sx automatically splits into a list,
2952 like '%sc -l'. The reason for this is to make it as easy as possible
2967 like '%sc -l'. The reason for this is to make it as easy as possible
2953 to process line-oriented shell output via further python commands.
2968 to process line-oriented shell output via further python commands.
2954 %sc is meant to provide much finer control, but requires more
2969 %sc is meant to provide much finer control, but requires more
2955 typing.
2970 typing.
2956
2971
2957 3) Just like %sc -l, this is a list with special attributes:
2972 3) Just like %sc -l, this is a list with special attributes:
2958
2973
2959 .l (or .list) : value as list.
2974 .l (or .list) : value as list.
2960 .n (or .nlstr): value as newline-separated string.
2975 .n (or .nlstr): value as newline-separated string.
2961 .s (or .spstr): value as whitespace-separated string.
2976 .s (or .spstr): value as whitespace-separated string.
2962
2977
2963 This is very useful when trying to use such lists as arguments to
2978 This is very useful when trying to use such lists as arguments to
2964 system commands."""
2979 system commands."""
2965
2980
2966 if parameter_s:
2981 if parameter_s:
2967 out,err = self.shell.getoutputerror(parameter_s)
2982 out,err = self.shell.getoutputerror(parameter_s)
2968 if err:
2983 if err:
2969 print >> Term.cerr,err
2984 print >> Term.cerr,err
2970 return SList(out.split('\n'))
2985 return SList(out.split('\n'))
2971
2986
2972 def magic_bg(self, parameter_s=''):
2987 def magic_bg(self, parameter_s=''):
2973 """Run a job in the background, in a separate thread.
2988 """Run a job in the background, in a separate thread.
2974
2989
2975 For example,
2990 For example,
2976
2991
2977 %bg myfunc(x,y,z=1)
2992 %bg myfunc(x,y,z=1)
2978
2993
2979 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2994 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2980 execution starts, a message will be printed indicating the job
2995 execution starts, a message will be printed indicating the job
2981 number. If your job number is 5, you can use
2996 number. If your job number is 5, you can use
2982
2997
2983 myvar = jobs.result(5) or myvar = jobs[5].result
2998 myvar = jobs.result(5) or myvar = jobs[5].result
2984
2999
2985 to assign this result to variable 'myvar'.
3000 to assign this result to variable 'myvar'.
2986
3001
2987 IPython has a job manager, accessible via the 'jobs' object. You can
3002 IPython has a job manager, accessible via the 'jobs' object. You can
2988 type jobs? to get more information about it, and use jobs.<TAB> to see
3003 type jobs? to get more information about it, and use jobs.<TAB> to see
2989 its attributes. All attributes not starting with an underscore are
3004 its attributes. All attributes not starting with an underscore are
2990 meant for public use.
3005 meant for public use.
2991
3006
2992 In particular, look at the jobs.new() method, which is used to create
3007 In particular, look at the jobs.new() method, which is used to create
2993 new jobs. This magic %bg function is just a convenience wrapper
3008 new jobs. This magic %bg function is just a convenience wrapper
2994 around jobs.new(), for expression-based jobs. If you want to create a
3009 around jobs.new(), for expression-based jobs. If you want to create a
2995 new job with an explicit function object and arguments, you must call
3010 new job with an explicit function object and arguments, you must call
2996 jobs.new() directly.
3011 jobs.new() directly.
2997
3012
2998 The jobs.new docstring also describes in detail several important
3013 The jobs.new docstring also describes in detail several important
2999 caveats associated with a thread-based model for background job
3014 caveats associated with a thread-based model for background job
3000 execution. Type jobs.new? for details.
3015 execution. Type jobs.new? for details.
3001
3016
3002 You can check the status of all jobs with jobs.status().
3017 You can check the status of all jobs with jobs.status().
3003
3018
3004 The jobs variable is set by IPython into the Python builtin namespace.
3019 The jobs variable is set by IPython into the Python builtin namespace.
3005 If you ever declare a variable named 'jobs', you will shadow this
3020 If you ever declare a variable named 'jobs', you will shadow this
3006 name. You can either delete your global jobs variable to regain
3021 name. You can either delete your global jobs variable to regain
3007 access to the job manager, or make a new name and assign it manually
3022 access to the job manager, or make a new name and assign it manually
3008 to the manager (stored in IPython's namespace). For example, to
3023 to the manager (stored in IPython's namespace). For example, to
3009 assign the job manager to the Jobs name, use:
3024 assign the job manager to the Jobs name, use:
3010
3025
3011 Jobs = __builtins__.jobs"""
3026 Jobs = __builtins__.jobs"""
3012
3027
3013 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3028 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3014
3029
3015 def magic_r(self, parameter_s=''):
3030 def magic_r(self, parameter_s=''):
3016 """Repeat previous input.
3031 """Repeat previous input.
3017
3032
3018 Note: Consider using the more powerfull %rep instead!
3033 Note: Consider using the more powerfull %rep instead!
3019
3034
3020 If given an argument, repeats the previous command which starts with
3035 If given an argument, repeats the previous command which starts with
3021 the same string, otherwise it just repeats the previous input.
3036 the same string, otherwise it just repeats the previous input.
3022
3037
3023 Shell escaped commands (with ! as first character) are not recognized
3038 Shell escaped commands (with ! as first character) are not recognized
3024 by this system, only pure python code and magic commands.
3039 by this system, only pure python code and magic commands.
3025 """
3040 """
3026
3041
3027 start = parameter_s.strip()
3042 start = parameter_s.strip()
3028 esc_magic = self.shell.ESC_MAGIC
3043 esc_magic = self.shell.ESC_MAGIC
3029 # Identify magic commands even if automagic is on (which means
3044 # Identify magic commands even if automagic is on (which means
3030 # the in-memory version is different from that typed by the user).
3045 # the in-memory version is different from that typed by the user).
3031 if self.shell.rc.automagic:
3046 if self.shell.rc.automagic:
3032 start_magic = esc_magic+start
3047 start_magic = esc_magic+start
3033 else:
3048 else:
3034 start_magic = start
3049 start_magic = start
3035 # Look through the input history in reverse
3050 # Look through the input history in reverse
3036 for n in range(len(self.shell.input_hist)-2,0,-1):
3051 for n in range(len(self.shell.input_hist)-2,0,-1):
3037 input = self.shell.input_hist[n]
3052 input = self.shell.input_hist[n]
3038 # skip plain 'r' lines so we don't recurse to infinity
3053 # skip plain 'r' lines so we don't recurse to infinity
3039 if input != '_ip.magic("r")\n' and \
3054 if input != '_ip.magic("r")\n' and \
3040 (input.startswith(start) or input.startswith(start_magic)):
3055 (input.startswith(start) or input.startswith(start_magic)):
3041 #print 'match',`input` # dbg
3056 #print 'match',`input` # dbg
3042 print 'Executing:',input,
3057 print 'Executing:',input,
3043 self.shell.runlines(input)
3058 self.shell.runlines(input)
3044 return
3059 return
3045 print 'No previous input matching `%s` found.' % start
3060 print 'No previous input matching `%s` found.' % start
3046
3061
3047
3062
3048 def magic_bookmark(self, parameter_s=''):
3063 def magic_bookmark(self, parameter_s=''):
3049 """Manage IPython's bookmark system.
3064 """Manage IPython's bookmark system.
3050
3065
3051 %bookmark <name> - set bookmark to current dir
3066 %bookmark <name> - set bookmark to current dir
3052 %bookmark <name> <dir> - set bookmark to <dir>
3067 %bookmark <name> <dir> - set bookmark to <dir>
3053 %bookmark -l - list all bookmarks
3068 %bookmark -l - list all bookmarks
3054 %bookmark -d <name> - remove bookmark
3069 %bookmark -d <name> - remove bookmark
3055 %bookmark -r - remove all bookmarks
3070 %bookmark -r - remove all bookmarks
3056
3071
3057 You can later on access a bookmarked folder with:
3072 You can later on access a bookmarked folder with:
3058 %cd -b <name>
3073 %cd -b <name>
3059 or simply '%cd <name>' if there is no directory called <name> AND
3074 or simply '%cd <name>' if there is no directory called <name> AND
3060 there is such a bookmark defined.
3075 there is such a bookmark defined.
3061
3076
3062 Your bookmarks persist through IPython sessions, but they are
3077 Your bookmarks persist through IPython sessions, but they are
3063 associated with each profile."""
3078 associated with each profile."""
3064
3079
3065 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3080 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3066 if len(args) > 2:
3081 if len(args) > 2:
3067 raise UsageError("%bookmark: too many arguments")
3082 raise UsageError("%bookmark: too many arguments")
3068
3083
3069 bkms = self.db.get('bookmarks',{})
3084 bkms = self.db.get('bookmarks',{})
3070
3085
3071 if opts.has_key('d'):
3086 if opts.has_key('d'):
3072 try:
3087 try:
3073 todel = args[0]
3088 todel = args[0]
3074 except IndexError:
3089 except IndexError:
3075 raise UsageError(
3090 raise UsageError(
3076 "%bookmark -d: must provide a bookmark to delete")
3091 "%bookmark -d: must provide a bookmark to delete")
3077 else:
3092 else:
3078 try:
3093 try:
3079 del bkms[todel]
3094 del bkms[todel]
3080 except KeyError:
3095 except KeyError:
3081 raise UsageError(
3096 raise UsageError(
3082 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3097 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3083
3098
3084 elif opts.has_key('r'):
3099 elif opts.has_key('r'):
3085 bkms = {}
3100 bkms = {}
3086 elif opts.has_key('l'):
3101 elif opts.has_key('l'):
3087 bks = bkms.keys()
3102 bks = bkms.keys()
3088 bks.sort()
3103 bks.sort()
3089 if bks:
3104 if bks:
3090 size = max(map(len,bks))
3105 size = max(map(len,bks))
3091 else:
3106 else:
3092 size = 0
3107 size = 0
3093 fmt = '%-'+str(size)+'s -> %s'
3108 fmt = '%-'+str(size)+'s -> %s'
3094 print 'Current bookmarks:'
3109 print 'Current bookmarks:'
3095 for bk in bks:
3110 for bk in bks:
3096 print fmt % (bk,bkms[bk])
3111 print fmt % (bk,bkms[bk])
3097 else:
3112 else:
3098 if not args:
3113 if not args:
3099 raise UsageError("%bookmark: You must specify the bookmark name")
3114 raise UsageError("%bookmark: You must specify the bookmark name")
3100 elif len(args)==1:
3115 elif len(args)==1:
3101 bkms[args[0]] = os.getcwd()
3116 bkms[args[0]] = os.getcwd()
3102 elif len(args)==2:
3117 elif len(args)==2:
3103 bkms[args[0]] = args[1]
3118 bkms[args[0]] = args[1]
3104 self.db['bookmarks'] = bkms
3119 self.db['bookmarks'] = bkms
3105
3120
3106 def magic_pycat(self, parameter_s=''):
3121 def magic_pycat(self, parameter_s=''):
3107 """Show a syntax-highlighted file through a pager.
3122 """Show a syntax-highlighted file through a pager.
3108
3123
3109 This magic is similar to the cat utility, but it will assume the file
3124 This magic is similar to the cat utility, but it will assume the file
3110 to be Python source and will show it with syntax highlighting. """
3125 to be Python source and will show it with syntax highlighting. """
3111
3126
3112 try:
3127 try:
3113 filename = get_py_filename(parameter_s)
3128 filename = get_py_filename(parameter_s)
3114 cont = file_read(filename)
3129 cont = file_read(filename)
3115 except IOError:
3130 except IOError:
3116 try:
3131 try:
3117 cont = eval(parameter_s,self.user_ns)
3132 cont = eval(parameter_s,self.user_ns)
3118 except NameError:
3133 except NameError:
3119 cont = None
3134 cont = None
3120 if cont is None:
3135 if cont is None:
3121 print "Error: no such file or variable"
3136 print "Error: no such file or variable"
3122 return
3137 return
3123
3138
3124 page(self.shell.pycolorize(cont),
3139 page(self.shell.pycolorize(cont),
3125 screen_lines=self.shell.rc.screen_length)
3140 screen_lines=self.shell.rc.screen_length)
3126
3141
3127 def magic_cpaste(self, parameter_s=''):
3142 def magic_cpaste(self, parameter_s=''):
3128 """Allows you to paste & execute a pre-formatted code block from clipboard
3143 """Allows you to paste & execute a pre-formatted code block from clipboard
3129
3144
3130 You must terminate the block with '--' (two minus-signs) alone on the
3145 You must terminate the block with '--' (two minus-signs) alone on the
3131 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3146 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3132 is the new sentinel for this operation)
3147 is the new sentinel for this operation)
3133
3148
3134 The block is dedented prior to execution to enable execution of method
3149 The block is dedented prior to execution to enable execution of method
3135 definitions. '>' and '+' characters at the beginning of a line are
3150 definitions. '>' and '+' characters at the beginning of a line are
3136 ignored, to allow pasting directly from e-mails or diff files. The
3151 ignored, to allow pasting directly from e-mails or diff files. The
3137 executed block is also assigned to variable named 'pasted_block' for
3152 executed block is also assigned to variable named 'pasted_block' for
3138 later editing with '%edit pasted_block'.
3153 later editing with '%edit pasted_block'.
3139
3154
3140 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3155 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3141 This assigns the pasted block to variable 'foo' as string, without
3156 This assigns the pasted block to variable 'foo' as string, without
3142 dedenting or executing it.
3157 dedenting or executing it.
3143
3158
3144 Do not be alarmed by garbled output on Windows (it's a readline bug).
3159 Do not be alarmed by garbled output on Windows (it's a readline bug).
3145 Just press enter and type -- (and press enter again) and the block
3160 Just press enter and type -- (and press enter again) and the block
3146 will be what was just pasted.
3161 will be what was just pasted.
3147
3162
3148 IPython statements (magics, shell escapes) are not supported (yet).
3163 IPython statements (magics, shell escapes) are not supported (yet).
3149 """
3164 """
3150 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3165 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3151 par = args.strip()
3166 par = args.strip()
3152 sentinel = opts.get('s','--')
3167 sentinel = opts.get('s','--')
3153
3168
3154 strip_from_start = [re.compile(e) for e in
3169 strip_from_start = [re.compile(e) for e in
3155 ['^(.?>)+','^In \[\d+\]:','^\++']]
3170 ['^(.?>)+','^In \[\d+\]:','^\++']]
3156 from IPython import iplib
3171 from IPython import iplib
3157 lines = []
3172 lines = []
3158 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3173 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3159 while 1:
3174 while 1:
3160 l = iplib.raw_input_original(':')
3175 l = iplib.raw_input_original(':')
3161 if l ==sentinel:
3176 if l ==sentinel:
3162 break
3177 break
3163
3178
3164 for pat in strip_from_start:
3179 for pat in strip_from_start:
3165 l = pat.sub('',l)
3180 l = pat.sub('',l)
3166 lines.append(l)
3181 lines.append(l)
3167
3182
3168 block = "\n".join(lines) + '\n'
3183 block = "\n".join(lines) + '\n'
3169 #print "block:\n",block
3184 #print "block:\n",block
3170 if not par:
3185 if not par:
3171 b = textwrap.dedent(block)
3186 b = textwrap.dedent(block)
3172 exec b in self.user_ns
3187 exec b in self.user_ns
3173 self.user_ns['pasted_block'] = b
3188 self.user_ns['pasted_block'] = b
3174 else:
3189 else:
3175 self.user_ns[par] = block
3190 self.user_ns[par] = block
3176 print "Block assigned to '%s'" % par
3191 print "Block assigned to '%s'" % par
3177
3192
3178 def magic_quickref(self,arg):
3193 def magic_quickref(self,arg):
3179 """ Show a quick reference sheet """
3194 """ Show a quick reference sheet """
3180 import IPython.usage
3195 import IPython.usage
3181 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3196 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3182
3197
3183 page(qr)
3198 page(qr)
3184
3199
3185 def magic_upgrade(self,arg):
3200 def magic_upgrade(self,arg):
3186 """ Upgrade your IPython installation
3201 """ Upgrade your IPython installation
3187
3202
3188 This will copy the config files that don't yet exist in your
3203 This will copy the config files that don't yet exist in your
3189 ipython dir from the system config dir. Use this after upgrading
3204 ipython dir from the system config dir. Use this after upgrading
3190 IPython if you don't wish to delete your .ipython dir.
3205 IPython if you don't wish to delete your .ipython dir.
3191
3206
3192 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3207 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3193 new users)
3208 new users)
3194
3209
3195 """
3210 """
3196 ip = self.getapi()
3211 ip = self.getapi()
3197 ipinstallation = path(IPython.__file__).dirname()
3212 ipinstallation = path(IPython.__file__).dirname()
3198 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3213 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3199 src_config = ipinstallation / 'UserConfig'
3214 src_config = ipinstallation / 'UserConfig'
3200 userdir = path(ip.options.ipythondir)
3215 userdir = path(ip.options.ipythondir)
3201 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3216 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3202 print ">",cmd
3217 print ">",cmd
3203 shell(cmd)
3218 shell(cmd)
3204 if arg == '-nolegacy':
3219 if arg == '-nolegacy':
3205 legacy = userdir.files('ipythonrc*')
3220 legacy = userdir.files('ipythonrc*')
3206 print "Nuking legacy files:",legacy
3221 print "Nuking legacy files:",legacy
3207
3222
3208 [p.remove() for p in legacy]
3223 [p.remove() for p in legacy]
3209 suffix = (sys.platform == 'win32' and '.ini' or '')
3224 suffix = (sys.platform == 'win32' and '.ini' or '')
3210 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3225 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3211
3226
3212
3227
3213 def magic_doctest_mode(self,parameter_s=''):
3228 def magic_doctest_mode(self,parameter_s=''):
3214 """Toggle doctest mode on and off.
3229 """Toggle doctest mode on and off.
3215
3230
3216 This mode allows you to toggle the prompt behavior between normal
3231 This mode allows you to toggle the prompt behavior between normal
3217 IPython prompts and ones that are as similar to the default IPython
3232 IPython prompts and ones that are as similar to the default IPython
3218 interpreter as possible.
3233 interpreter as possible.
3219
3234
3220 It also supports the pasting of code snippets that have leading '>>>'
3235 It also supports the pasting of code snippets that have leading '>>>'
3221 and '...' prompts in them. This means that you can paste doctests from
3236 and '...' prompts in them. This means that you can paste doctests from
3222 files or docstrings (even if they have leading whitespace), and the
3237 files or docstrings (even if they have leading whitespace), and the
3223 code will execute correctly. You can then use '%history -tn' to see
3238 code will execute correctly. You can then use '%history -tn' to see
3224 the translated history without line numbers; this will give you the
3239 the translated history without line numbers; this will give you the
3225 input after removal of all the leading prompts and whitespace, which
3240 input after removal of all the leading prompts and whitespace, which
3226 can be pasted back into an editor.
3241 can be pasted back into an editor.
3227
3242
3228 With these features, you can switch into this mode easily whenever you
3243 With these features, you can switch into this mode easily whenever you
3229 need to do testing and changes to doctests, without having to leave
3244 need to do testing and changes to doctests, without having to leave
3230 your existing IPython session.
3245 your existing IPython session.
3231 """
3246 """
3232
3247
3233 # XXX - Fix this to have cleaner activate/deactivate calls.
3248 # XXX - Fix this to have cleaner activate/deactivate calls.
3234 from IPython.Extensions import InterpreterPasteInput as ipaste
3249 from IPython.Extensions import InterpreterPasteInput as ipaste
3235 from IPython.ipstruct import Struct
3250 from IPython.ipstruct import Struct
3236
3251
3237 # Shorthands
3252 # Shorthands
3238 shell = self.shell
3253 shell = self.shell
3239 oc = shell.outputcache
3254 oc = shell.outputcache
3240 rc = shell.rc
3255 rc = shell.rc
3241 meta = shell.meta
3256 meta = shell.meta
3242 # dstore is a data store kept in the instance metadata bag to track any
3257 # dstore is a data store kept in the instance metadata bag to track any
3243 # changes we make, so we can undo them later.
3258 # changes we make, so we can undo them later.
3244 dstore = meta.setdefault('doctest_mode',Struct())
3259 dstore = meta.setdefault('doctest_mode',Struct())
3245 save_dstore = dstore.setdefault
3260 save_dstore = dstore.setdefault
3246
3261
3247 # save a few values we'll need to recover later
3262 # save a few values we'll need to recover later
3248 mode = save_dstore('mode',False)
3263 mode = save_dstore('mode',False)
3249 save_dstore('rc_pprint',rc.pprint)
3264 save_dstore('rc_pprint',rc.pprint)
3250 save_dstore('xmode',shell.InteractiveTB.mode)
3265 save_dstore('xmode',shell.InteractiveTB.mode)
3251 save_dstore('rc_separate_out',rc.separate_out)
3266 save_dstore('rc_separate_out',rc.separate_out)
3252 save_dstore('rc_separate_out2',rc.separate_out2)
3267 save_dstore('rc_separate_out2',rc.separate_out2)
3253 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3268 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3254
3269
3255 if mode == False:
3270 if mode == False:
3256 # turn on
3271 # turn on
3257 ipaste.activate_prefilter()
3272 ipaste.activate_prefilter()
3258
3273
3259 oc.prompt1.p_template = '>>> '
3274 oc.prompt1.p_template = '>>> '
3260 oc.prompt2.p_template = '... '
3275 oc.prompt2.p_template = '... '
3261 oc.prompt_out.p_template = ''
3276 oc.prompt_out.p_template = ''
3262
3277
3263 oc.output_sep = ''
3278 oc.output_sep = ''
3264 oc.output_sep2 = ''
3279 oc.output_sep2 = ''
3265
3280
3266 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3281 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3267 oc.prompt_out.pad_left = False
3282 oc.prompt_out.pad_left = False
3268
3283
3269 rc.pprint = False
3284 rc.pprint = False
3270
3285
3271 shell.magic_xmode('Plain')
3286 shell.magic_xmode('Plain')
3272
3287
3273 else:
3288 else:
3274 # turn off
3289 # turn off
3275 ipaste.deactivate_prefilter()
3290 ipaste.deactivate_prefilter()
3276
3291
3277 oc.prompt1.p_template = rc.prompt_in1
3292 oc.prompt1.p_template = rc.prompt_in1
3278 oc.prompt2.p_template = rc.prompt_in2
3293 oc.prompt2.p_template = rc.prompt_in2
3279 oc.prompt_out.p_template = rc.prompt_out
3294 oc.prompt_out.p_template = rc.prompt_out
3280
3295
3281 oc.output_sep = dstore.rc_separate_out
3296 oc.output_sep = dstore.rc_separate_out
3282 oc.output_sep2 = dstore.rc_separate_out2
3297 oc.output_sep2 = dstore.rc_separate_out2
3283
3298
3284 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3299 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3285 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3300 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3286
3301
3287 rc.pprint = dstore.rc_pprint
3302 rc.pprint = dstore.rc_pprint
3288
3303
3289 shell.magic_xmode(dstore.xmode)
3304 shell.magic_xmode(dstore.xmode)
3290
3305
3291 # Store new mode and inform
3306 # Store new mode and inform
3292 dstore.mode = bool(1-int(mode))
3307 dstore.mode = bool(1-int(mode))
3293 print 'Doctest mode is:',
3308 print 'Doctest mode is:',
3294 print ['OFF','ON'][dstore.mode]
3309 print ['OFF','ON'][dstore.mode]
3295
3310
3296 # end Magic
3311 # end Magic
@@ -1,203 +1,203 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 r""" mglob - enhanced file list expansion module
3 r""" mglob - enhanced file list expansion module
4
4
5 Use as stand-alone utility (for xargs, `backticks` etc.),
5 Use as stand-alone utility (for xargs, `backticks` etc.),
6 or a globbing library for own python programs. Globbing the sys.argv is something
6 or a globbing library for own python programs. Globbing the sys.argv is something
7 that almost every Windows script has to perform manually, and this module is here
7 that almost every Windows script has to perform manually, and this module is here
8 to help with that task. Also Unix users will benefit from enhanced modes
8 to help with that task. Also Unix users will benefit from enhanced modes
9 such as recursion, exclusion, directory omission...
9 such as recursion, exclusion, directory omission...
10
10
11 Unlike glob.glob, directories are not included in the glob unless specified
11 Unlike glob.glob, directories are not included in the glob unless specified
12 with 'dir:'
12 with 'dir:'
13
13
14 'expand' is the function to use in python programs. Typical use
14 'expand' is the function to use in python programs. Typical use
15 to expand argv (esp. in windows)::
15 to expand argv (esp. in windows)::
16
16
17 try:
17 try:
18 import mglob
18 import mglob
19 files = mglob.expand(sys.argv[1:])
19 files = mglob.expand(sys.argv[1:])
20 except ImportError:
20 except ImportError:
21 print "mglob not found; try 'easy_install mglob' for extra features"
21 print "mglob not found; try 'easy_install mglob' for extra features"
22 files = sys.argv[1:]
22 files = sys.argv[1:]
23
23
24 Note that for unix, shell expands *normal* wildcards (*.cpp, etc.) in argv.
24 Note that for unix, shell expands *normal* wildcards (*.cpp, etc.) in argv.
25 Therefore, you might want to use quotes with normal wildcards to prevent this
25 Therefore, you might want to use quotes with normal wildcards to prevent this
26 expansion, in order for mglob to see the wildcards and get the wanted behaviour.
26 expansion, in order for mglob to see the wildcards and get the wanted behaviour.
27 Not quoting the wildcards is harmless and typically has equivalent results, though.
27 Not quoting the wildcards is harmless and typically has equivalent results, though.
28
28
29 Author: Ville Vainio <vivainio@gmail.com>
29 Author: Ville Vainio <vivainio@gmail.com>
30 License: MIT Open Source license
30 License: MIT Open Source license
31
31
32 """
32 """
33
33
34 #Assigned in variable for "usage" printing convenience"
34 #Assigned in variable for "usage" printing convenience"
35
35
36 globsyntax = """\
36 globsyntax = """\
37 This program allows specifying filenames with "mglob" mechanism.
37 This program allows specifying filenames with "mglob" mechanism.
38 Supported syntax in globs (wilcard matching patterns)::
38 Supported syntax in globs (wilcard matching patterns)::
39
39
40 *.cpp ?ellowo*
40 *.cpp ?ellowo*
41 - obvious. Differs from normal glob in that dirs are not included.
41 - obvious. Differs from normal glob in that dirs are not included.
42 Unix users might want to write this as: "*.cpp" "?ellowo*"
42 Unix users might want to write this as: "*.cpp" "?ellowo*"
43 rec:/usr/share=*.txt,*.doc
43 rec:/usr/share=*.txt,*.doc
44 - get all *.txt and *.doc under /usr/share,
44 - get all *.txt and *.doc under /usr/share,
45 recursively
45 recursively
46 rec:/usr/share
46 rec:/usr/share
47 - All files under /usr/share, recursively
47 - All files under /usr/share, recursively
48 rec:*.py
48 rec:*.py
49 - All .py files under current working dir, recursively
49 - All .py files under current working dir, recursively
50 foo
50 foo
51 - File or dir foo
51 - File or dir foo
52 !*.bak readme*
52 !*.bak readme*
53 - readme*, exclude files ending with .bak
53 - readme*, exclude files ending with .bak
54 !.svn/ !.hg/ !*_Data/ rec:.
54 !.svn/ !.hg/ !*_Data/ rec:.
55 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
55 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
56 Trailing / is the key, \ does not work!
56 Trailing / is the key, \ does not work!
57 dir:foo
57 dir:foo
58 - the directory foo if it exists (not files in foo)
58 - the directory foo if it exists (not files in foo)
59 dir:*
59 dir:*
60 - all directories in current folder
60 - all directories in current folder
61 foo.py bar.* !h* rec:*.py
61 foo.py bar.* !h* rec:*.py
62 - Obvious. !h* exclusion only applies for rec:*.py.
62 - Obvious. !h* exclusion only applies for rec:*.py.
63 foo.py is *not* included twice.
63 foo.py is *not* included twice.
64 @filelist.txt
64 @filelist.txt
65 - All files listed in 'filelist.txt' file, on separate lines.
65 - All files listed in 'filelist.txt' file, on separate lines.
66 """
66 """
67
67
68
68
69 __version__ = "0.2"
69 __version__ = "0.2"
70
70
71
71
72 import os,glob,fnmatch,sys
72 import os,glob,fnmatch,sys
73 from sets import Set as set
73 from sets import Set as set
74
74
75
75
76 def expand(flist,exp_dirs = False):
76 def expand(flist,exp_dirs = False):
77 """ Expand the glob(s) in flist.
77 """ Expand the glob(s) in flist.
78
78
79 flist may be either a whitespace-separated list of globs/files
79 flist may be either a whitespace-separated list of globs/files
80 or an array of globs/files.
80 or an array of globs/files.
81
81
82 if exp_dirs is true, directory names in glob are expanded to the files
82 if exp_dirs is true, directory names in glob are expanded to the files
83 contained in them - otherwise, directory names are returned as is.
83 contained in them - otherwise, directory names are returned as is.
84
84
85 """
85 """
86 if isinstance(flist, basestring):
86 if isinstance(flist, basestring):
87 flist = flist.split()
87 flist = flist.split()
88 done_set = set()
88 done_set = set()
89 denied_set = set()
89 denied_set = set()
90
90
91 def recfind(p, pats = ["*"]):
91 def recfind(p, pats = ["*"]):
92 denied_dirs = ["*" + d+"*" for d in denied_set if d.endswith("/")]
92 denied_dirs = ["*" + d+"*" for d in denied_set if d.endswith("/")]
93 #print "de", denied_dirs
93 #print "de", denied_dirs
94 for (dp,dnames,fnames) in os.walk(p):
94 for (dp,dnames,fnames) in os.walk(p):
95 # see if we should ignore the whole directory
95 # see if we should ignore the whole directory
96 dp_norm = dp.replace("\\","/") + "/"
96 dp_norm = dp.replace("\\","/") + "/"
97 deny = False
97 deny = False
98 #print "dp",dp
98 #print "dp",dp
99 for deny_pat in denied_dirs:
99 for deny_pat in denied_dirs:
100 if fnmatch.fnmatch( dp_norm, deny_pat):
100 if fnmatch.fnmatch( dp_norm, deny_pat):
101 deny = True
101 deny = True
102 break
102 break
103 if deny:
103 if deny:
104 continue
104 continue
105
105
106
106
107 for f in fnames:
107 for f in fnames:
108 matched = False
108 matched = False
109 for p in pats:
109 for p in pats:
110 if fnmatch.fnmatch(f,p):
110 if fnmatch.fnmatch(f,p):
111 matched = True
111 matched = True
112 break
112 break
113 if matched:
113 if matched:
114 yield os.path.join(dp,f)
114 yield os.path.join(dp,f)
115
115
116 def once_filter(seq):
116 def once_filter(seq):
117 for it in seq:
117 for it in seq:
118 p = os.path.abspath(it)
118 p = os.path.abspath(it)
119 if p in done_set:
119 if p in done_set:
120 continue
120 continue
121 done_set.add(p)
121 done_set.add(p)
122 deny = False
122 deny = False
123 for deny_pat in denied_set:
123 for deny_pat in denied_set:
124 if fnmatch.fnmatch(os.path.basename(p), deny_pat):
124 if fnmatch.fnmatch(os.path.basename(p), deny_pat):
125 deny = True
125 deny = True
126 break
126 break
127 if not deny:
127 if not deny:
128 yield it
128 yield it
129 return
129 return
130
130
131 res = []
131 res = []
132
132
133 for ent in flist:
133 for ent in flist:
134 ent = os.path.expanduser(os.path.expandvars(ent))
134 ent = os.path.expanduser(os.path.expandvars(ent))
135 if ent.lower().startswith('rec:'):
135 if ent.lower().startswith('rec:'):
136 fields = ent[4:].split('=')
136 fields = ent[4:].split('=')
137 if len(fields) == 2:
137 if len(fields) == 2:
138 pth, patlist = fields
138 pth, patlist = fields
139 elif len(fields) == 1:
139 elif len(fields) == 1:
140 if os.path.isdir(fields[0]):
140 if os.path.isdir(fields[0]):
141 # single arg is dir
141 # single arg is dir
142 pth, patlist = fields[0], '*'
142 pth, patlist = fields[0], '*'
143 else:
143 else:
144 # single arg is pattern
144 # single arg is pattern
145 pth, patlist = '.', fields[0]
145 pth, patlist = '.', fields[0]
146
146
147 elif len(fields) == 0:
147 elif len(fields) == 0:
148 pth, pathlist = '.','*'
148 pth, pathlist = '.','*'
149
149
150 pats = patlist.split(',')
150 pats = patlist.split(',')
151 res.extend(once_filter(recfind(pth, pats)))
151 res.extend(once_filter(recfind(pth, pats)))
152 # filelist
152 # filelist
153 elif ent.startswith('@') and os.path.isfile(ent[1:]):
153 elif ent.startswith('@') and os.path.isfile(ent[1:]):
154 res.extend(once_filter(open(ent[1:]).read().splitlines()))
154 res.extend(once_filter(open(ent[1:]).read().splitlines()))
155 # exclusion
155 # exclusion
156 elif ent.startswith('!'):
156 elif ent.startswith('!'):
157 denied_set.add(ent[1:])
157 denied_set.add(ent[1:])
158 # glob only dirs
158 # glob only dirs
159 elif ent.lower().startswith('dir:'):
159 elif ent.lower().startswith('dir:'):
160 res.extend(once_filter(filter(os.path.isdir,glob.glob(ent[4:]))))
160 res.extend(once_filter(filter(os.path.isdir,glob.glob(ent[4:]))))
161
161
162 # get all files in the specified dir
162 # get all files in the specified dir
163 elif os.path.isdir(ent) and exp_dirs:
163 elif os.path.isdir(ent) and exp_dirs:
164 res.extend(once_filter(filter(os.path.isfile,glob.glob(ent + os.sep+"*"))))
164 res.extend(once_filter(filter(os.path.isfile,glob.glob(ent + os.sep+"*"))))
165
165
166 # glob only files
166 # glob only files
167
167
168 elif '*' in ent or '?' in ent:
168 elif '*' in ent or '?' in ent:
169 res.extend(once_filter(filter(os.path.isfile,glob.glob(ent))))
169 res.extend(once_filter(filter(os.path.isfile,glob.glob(ent))))
170
170
171 else:
171 else:
172 res.extend(once_filter([ent]))
172 res.extend(once_filter([ent]))
173 return res
173 return res
174
174
175
175
176 def test():
176 def test():
177 assert (
177 assert (
178 expand("*.py ~/.ipython/*.py rec:/usr/share/doc-base") ==
178 expand("*.py ~/.ipython/*.py rec:/usr/share/doc-base") ==
179 expand( ['*.py', '~/.ipython/*.py', 'rec:/usr/share/doc-base'] )
179 expand( ['*.py', '~/.ipython/*.py', 'rec:/usr/share/doc-base'] )
180 )
180 )
181
181
182 def main():
182 def main():
183 if len(sys.argv) < 2:
183 if len(sys.argv) < 2:
184 print globsyntax
184 print globsyntax
185 return
185 return
186
186
187 print "\n".join(expand(sys.argv[1:])),
187 print "\n".join(expand(sys.argv[1:])),
188
188
189 def mglob_f(self, arg):
189 def mglob_f(self, arg):
190 from IPython.genutils import SList
190 from IPython.genutils import SList
191 if arg.strip():
191 if arg.strip():
192 return SList(expand(arg))
192 return SList(expand(arg))
193 print "Please specify pattern!"
193 print "Please specify pattern!"
194 print globsyntax
194 print globsyntax
195
195
196 def init_ipython(ip):
196 def init_ipython(ip):
197 """ register %mglob for IPython """
197 """ register %mglob for IPython """
198 mglob_f.__doc__ = globsyntax
198 mglob_f.__doc__ = globsyntax
199 ip.expose_magic("mglob",mglob_f)
199 ip.expose_magic("mglob",mglob_f)
200
200
201 # test()
201 # test()
202 if __name__ == "__main__":
202 if __name__ == "__main__":
203 main()
203 main()
This diff has been collapsed as it changes many lines, (3716 lines changed) Show them Hide them
@@ -1,5456 +1,5860 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 Welcome to IPython's documentation!
5 IPython documentation
6 ===================================
6 =====================
7
7
8 Contents:
8 Contents:
9
9
10 .. toctree::
10 .. toctree::
11 :maxdepth: 2
11 :maxdepth: 2
12
12
13 Indices and tables
13 Indices and tables
14 ==================
14 ==================
15
15
16 * :ref:`genindex`
16 * :ref:`genindex`
17 * :ref:`modindex`
17 * :ref:`modindex`
18 * :ref:`search`
18 * :ref:`search`
19
19
20 Overview
20 Overview
21 ========
21 ========
22
22
23 One of Python's most useful features is its interactive interpreter.
23 One of Python's most useful features is its interactive interpreter.
24 This system allows very fast testing of ideas without the overhead of
24 This system allows very fast testing of ideas without the overhead of
25 creating test files as is typical in most programming languages.
25 creating test files as is typical in most programming languages.
26 However, the interpreter supplied with the standard Python distribution
26 However, the interpreter supplied with the standard Python distribution
27 is somewhat limited for extended interactive use.
27 is somewhat limited for extended interactive use.
28
28
29 IPython is a free software project (released under the BSD license)
29 IPython is a free software project (released under the BSD license)
30 which tries to:
30 which tries to:
31
31
32 1. Provide an interactive shell superior to Python's default. IPython
32 1. Provide an interactive shell superior to Python's default. IPython
33 has many features for object introspection, system shell access,
33 has many features for object introspection, system shell access,
34 and its own special command system for adding functionality when
34 and its own special command system for adding functionality when
35 working interactively. It tries to be a very efficient environment
35 working interactively. It tries to be a very efficient environment
36 both for Python code development and for exploration of problems
36 both for Python code development and for exploration of problems
37 using Python objects (in situations like data analysis).
37 using Python objects (in situations like data analysis).
38 2. Serve as an embeddable, ready to use interpreter for your own
38 2. Serve as an embeddable, ready to use interpreter for your own
39 programs. IPython can be started with a single call from inside
39 programs. IPython can be started with a single call from inside
40 another program, providing access to the current namespace. This
40 another program, providing access to the current namespace. This
41 can be very useful both for debugging purposes and for situations
41 can be very useful both for debugging purposes and for situations
42 where a blend of batch-processing and interactive exploration are
42 where a blend of batch-processing and interactive exploration are
43 needed.
43 needed.
44 3. Offer a flexible framework which can be used as the base
44 3. Offer a flexible framework which can be used as the base
45 environment for other systems with Python as the underlying
45 environment for other systems with Python as the underlying
46 language. Specifically scientific environments like Mathematica,
46 language. Specifically scientific environments like Mathematica,
47 IDL and Matlab inspired its design, but similar ideas can be
47 IDL and Matlab inspired its design, but similar ideas can be
48 useful in many fields.
48 useful in many fields.
49 4. Allow interactive testing of threaded graphical toolkits. IPython
49 4. Allow interactive testing of threaded graphical toolkits. IPython
50 has support for interactive, non-blocking control of GTK, Qt and
50 has support for interactive, non-blocking control of GTK, Qt and
51 WX applications via special threading flags. The normal Python
51 WX applications via special threading flags. The normal Python
52 shell can only do this for Tkinter applications.
52 shell can only do this for Tkinter applications.
53
53
54
54
55 Main features
55 Main features
56 -------------
56 -------------
57
57
58 * Dynamic object introspection. One can access docstrings, function
58 * Dynamic object introspection. One can access docstrings, function
59 definition prototypes, source code, source files and other details
59 definition prototypes, source code, source files and other details
60 of any object accessible to the interpreter with a single
60 of any object accessible to the interpreter with a single
61 keystroke ('?', and using '??' provides additional detail).
61 keystroke ('?', and using '??' provides additional detail).
62 * Searching through modules and namespaces with '*' wildcards, both
62 * Searching through modules and namespaces with '*' wildcards, both
63 when using the '?' system and via the %psearch command.
63 when using the '?' system and via the %psearch command.
64 * Completion in the local namespace, by typing TAB at the prompt.
64 * Completion in the local namespace, by typing TAB at the prompt.
65 This works for keywords, methods, variables and files in the
65 This works for keywords, modules, methods, variables and files in the
66 current directory. This is supported via the readline library, and
66 current directory. This is supported via the readline library, and
67 full access to configuring readline's behavior is provided.
67 full access to configuring readline's behavior is provided.
68 Custom completers can be implemented easily for different purposes
69 (system commands, magic arguments etc.)
68 * Numbered input/output prompts with command history (persistent
70 * Numbered input/output prompts with command history (persistent
69 across sessions and tied to each profile), full searching in this
71 across sessions and tied to each profile), full searching in this
70 history and caching of all input and output.
72 history and caching of all input and output.
71 * User-extensible 'magic' commands. A set of commands prefixed with
73 * User-extensible 'magic' commands. A set of commands prefixed with
72 % is available for controlling IPython itself and provides
74 % is available for controlling IPython itself and provides
73 directory control, namespace information and many aliases to
75 directory control, namespace information and many aliases to
74 common system shell commands.
76 common system shell commands.
75 * Alias facility for defining your own system aliases.
77 * Alias facility for defining your own system aliases.
76 * Complete system shell access. Lines starting with ! are passed
78 * Complete system shell access. Lines starting with ! are passed
77 directly to the system shell, and using !! captures shell output
79 directly to the system shell, and using !! or var = !cmd
78 into python variables for further use.
80 captures shell output into python variables for further use.
79 * Background execution of Python commands in a separate thread.
81 * Background execution of Python commands in a separate thread.
80 IPython has an internal job manager called jobs, and a
82 IPython has an internal job manager called jobs, and a
81 conveninence backgrounding magic function called %bg.
83 conveninence backgrounding magic function called %bg.
82 * The ability to expand python variables when calling the system
84 * The ability to expand python variables when calling the system
83 shell. In a shell command, any python variable prefixed with $ is
85 shell. In a shell command, any python variable prefixed with $ is
84 expanded. A double $$ allows passing a literal $ to the shell (for
86 expanded. A double $$ allows passing a literal $ to the shell (for
85 access to shell and environment variables like $PATH).
87 access to shell and environment variables like $PATH).
86 * Filesystem navigation, via a magic %cd command, along with a
88 * Filesystem navigation, via a magic %cd command, along with a
87 persistent bookmark system (using %bookmark) for fast access to
89 persistent bookmark system (using %bookmark) for fast access to
88 frequently visited directories.
90 frequently visited directories.
89 * A lightweight persistence framework via the %store command, which
91 * A lightweight persistence framework via the %store command, which
90 allows you to save arbitrary Python variables. These get restored
92 allows you to save arbitrary Python variables. These get restored
91 automatically when your session restarts.
93 automatically when your session restarts.
92 * Automatic indentation (optional) of code as you type (through the
94 * Automatic indentation (optional) of code as you type (through the
93 readline library).
95 readline library).
94 * Macro system for quickly re-executing multiple lines of previous
96 * Macro system for quickly re-executing multiple lines of previous
95 input with a single name. Macros can be stored persistently via
97 input with a single name. Macros can be stored persistently via
96 %store and edited via %edit.
98 %store and edited via %edit.
97 * Session logging (you can then later use these logs as code in your
99 * Session logging (you can then later use these logs as code in your
98 programs). Logs can optionally timestamp all input, and also store
100 programs). Logs can optionally timestamp all input, and also store
99 session output (marked as comments, so the log remains valid
101 session output (marked as comments, so the log remains valid
100 Python source code).
102 Python source code).
101 * Session restoring: logs can be replayed to restore a previous
103 * Session restoring: logs can be replayed to restore a previous
102 session to the state where you left it.
104 session to the state where you left it.
103 * Verbose and colored exception traceback printouts. Easier to parse
105 * Verbose and colored exception traceback printouts. Easier to parse
104 visually, and in verbose mode they produce a lot of useful
106 visually, and in verbose mode they produce a lot of useful
105 debugging information (basically a terminal version of the cgitb
107 debugging information (basically a terminal version of the cgitb
106 module).
108 module).
107 * Auto-parentheses: callable objects can be executed without
109 * Auto-parentheses: callable objects can be executed without
108 parentheses: 'sin 3' is automatically converted to 'sin(3)'.
110 parentheses: 'sin 3' is automatically converted to 'sin(3)'.
109 * Auto-quoting: using ',' or ';' as the first character forces
111 * Auto-quoting: using ',' or ';' as the first character forces
110 auto-quoting of the rest of the line: ',my_function a b' becomes
112 auto-quoting of the rest of the line: ',my_function a b' becomes
111 automatically 'my_function("a","b")', while ';my_function a b'
113 automatically 'my_function("a","b")', while ';my_function a b'
112 becomes 'my_function("a b")'.
114 becomes 'my_function("a b")'.
113 * Extensible input syntax. You can define filters that pre-process
115 * Extensible input syntax. You can define filters that pre-process
114 user input to simplify input in special situations. This allows
116 user input to simplify input in special situations. This allows
115 for example pasting multi-line code fragments which start with
117 for example pasting multi-line code fragments which start with
116 '>>>' or '...' such as those from other python sessions or the
118 '>>>' or '...' such as those from other python sessions or the
117 standard Python documentation.
119 standard Python documentation.
118 * Flexible configuration system. It uses a configuration file which
120 * Flexible configuration system. It uses a configuration file which
119 allows permanent setting of all command-line options, module
121 allows permanent setting of all command-line options, module
120 loading, code and file execution. The system allows recursive file
122 loading, code and file execution. The system allows recursive file
121 inclusion, so you can have a base file with defaults and layers
123 inclusion, so you can have a base file with defaults and layers
122 which load other customizations for particular projects.
124 which load other customizations for particular projects.
123 * Embeddable. You can call IPython as a python shell inside your own
125 * Embeddable. You can call IPython as a python shell inside your own
124 python programs. This can be used both for debugging code or for
126 python programs. This can be used both for debugging code or for
125 providing interactive abilities to your programs with knowledge
127 providing interactive abilities to your programs with knowledge
126 about the local namespaces (very useful in debugging and data
128 about the local namespaces (very useful in debugging and data
127 analysis situations).
129 analysis situations).
128 * Easy debugger access. You can set IPython to call up an enhanced
130 * Easy debugger access. You can set IPython to call up an enhanced
129 version of the Python debugger (pdb) every time there is an
131 version of the Python debugger (pdb) every time there is an
130 uncaught exception. This drops you inside the code which triggered
132 uncaught exception. This drops you inside the code which triggered
131 the exception with all the data live and it is possible to
133 the exception with all the data live and it is possible to
132 navigate the stack to rapidly isolate the source of a bug. The
134 navigate the stack to rapidly isolate the source of a bug. The
133 %run magic command -with the -d option- can run any script under
135 %run magic command -with the -d option- can run any script under
134 pdb's control, automatically setting initial breakpoints for you.
136 pdb's control, automatically setting initial breakpoints for you.
135 This version of pdb has IPython-specific improvements, including
137 This version of pdb has IPython-specific improvements, including
136 tab-completion and traceback coloring support.
138 tab-completion and traceback coloring support. For even easier
139 debugger access, try %debug after seeing an exception. winpdb is
140 also supported, see ipy_winpdb extension.
137 * Profiler support. You can run single statements (similar to
141 * Profiler support. You can run single statements (similar to
138 profile.run()) or complete programs under the profiler's control.
142 profile.run()) or complete programs under the profiler's control.
139 While this is possible with standard cProfile or profile modules,
143 While this is possible with standard cProfile or profile modules,
140 IPython wraps this functionality with magic commands (see '%prun'
144 IPython wraps this functionality with magic commands (see '%prun'
141 and '%run -p') convenient for rapid interactive work.
145 and '%run -p') convenient for rapid interactive work.
142 * Doctest support. The special %doctest_mode command toggles a mode
146 * Doctest support. The special %doctest_mode command toggles a mode
143 that allows you to paste existing doctests (with leading '>>>'
147 that allows you to paste existing doctests (with leading '>>>'
144 prompts and whitespace) and uses doctest-compatible prompts and
148 prompts and whitespace) and uses doctest-compatible prompts and
145 output, so you can use IPython sessions as doctest code.
149 output, so you can use IPython sessions as doctest code.
146
150
147
151
148 Portability and Python requirements
152 Portability and Python requirements
149 -----------------------------------
153 -----------------------------------
150
154
151 Python requirements: IPython requires with Python version 2.3 or newer.
155 Python requirements: IPython requires with Python version 2.3 or newer.
152 If you are still using Python 2.2 and can not upgrade, the last version
156 If you are still using Python 2.2 and can not upgrade, the last version
153 of IPython which worked with Python 2.2 was 0.6.15, so you will have to
157 of IPython which worked with Python 2.2 was 0.6.15, so you will have to
154 use that.
158 use that.
155
159
156 IPython is developed under Linux, but it should work in any reasonable
160 IPython is developed under Linux, but it should work in any reasonable
157 Unix-type system (tested OK under Solaris and the BSD family, for which
161 Unix-type system (tested OK under Solaris and the BSD family, for which
158 a port exists thanks to Dryice Liu).
162 a port exists thanks to Dryice Liu).
159
163
160 Mac OS X: it works, apparently without any problems (thanks to Jim Boyle
164 Mac OS X: it works, apparently without any problems (thanks to Jim Boyle
161 at Lawrence Livermore for the information). Thanks to Andrea Riciputi,
165 at Lawrence Livermore for the information). Thanks to Andrea Riciputi,
162 Fink support is available.
166 Fink support is available.
163
167
164 CygWin: it works mostly OK, though some users have reported problems
168 CygWin: it works mostly OK, though some users have reported problems
165 with prompt coloring. No satisfactory solution to this has been found so
169 with prompt coloring. No satisfactory solution to this has been found so
166 far, you may want to disable colors permanently in the ipythonrc
170 far, you may want to disable colors permanently in the ipythonrc
167 configuration file if you experience problems. If you have proper color
171 configuration file if you experience problems. If you have proper color
168 support under cygwin, please post to the IPython mailing list so this
172 support under cygwin, please post to the IPython mailing list so this
169 issue can be resolved for all users.
173 issue can be resolved for all users.
170
174
171 Windows: it works well under Windows XP/2k, and I suspect NT should
175 Windows: it works well under Windows Vista/XP/2k, and I suspect NT should
172 behave similarly. Section 2.3 <node2.html#sub:Under-Windows> describes
176 behave similarly. Section "Installation under windows" describes
173 installation details for Windows, including some additional tools needed
177 installation details for Windows, including some additional tools needed
174 on this platform.
178 on this platform.
175
179
176 Windows 9x support is present, and has been reported to work fine (at
180 Windows 9x support is present, and has been reported to work fine (at
177 least on WinME).
181 least on WinME).
178
182
179 Note, that I have very little access to and experience with Windows
180 development. However, an excellent group of Win32 users (led by Ville
181 Vainio), consistently contribute bugfixes and platform-specific
182 enhancements, so they more than make up for my deficiencies on that
183 front. In fact, Win32 users report using IPython as a system shell (see
184 Sec. 12 <node12.html#sec:IPython-as-shell> for details), as it offers a
185 level of control and features which the default cmd.exe doesn't provide.
186
187
188 Location
183 Location
189 ========
184 ========
190
185
191 IPython is generously hosted at http://ipython.scipy.org by the
186 IPython is generously hosted at http://ipython.scipy.org by the
192 Enthought, Inc and the SciPy project. This site offers downloads,
187 Enthought, Inc and the SciPy project. This site offers downloads,
193 subversion access, mailing lists and a bug tracking system. I am very
188 subversion access, mailing lists and a bug tracking system. I am very
194 grateful to Enthought (http://www.enthought.com) and all of the SciPy
189 grateful to Enthought (http://www.enthought.com) and all of the SciPy
195 team for their contribution.
190 team for their contribution.
196
191
197 Installation
192 Installation
198 ============
193 ============
199
194
200 Instant instructions
195 Instant instructions
201 --------------------
196 --------------------
202
197
203 If you are of the impatient kind, under Linux/Unix simply untar/unzip
198 If you are of the impatient kind, under Linux/Unix simply untar/unzip
204 the download, then install with 'python setup.py install'. Under
199 the download, then install with 'python setup.py install'. Under
205 Windows, double-click on the provided .exe binary installer.
200 Windows, double-click on the provided .exe binary installer.
206
201
207 Then, take a look at Sections 3 <node3.html#sec:good_config> for
202 Then, take a look at Customization_ section for configuring things
208 configuring things optimally and 4 <node4.html#sec:quick_tips> for quick
203 optimally and `Quick tips`_ for quick tips on efficient use of
209 tips on efficient use of IPython. You can later refer to the rest of the
204 IPython. You can later refer to the rest of the manual for all the
210 manual for all the gory details.
205 gory details.
211
206
212 See the notes in sec. 2.4 <#sec:upgrade> for upgrading IPython versions.
207 See the notes in upgrading_ section for upgrading IPython versions.
213
208
214
209
215 Detailed Unix instructions (Linux, Mac OS X, etc.)
210 Detailed Unix instructions (Linux, Mac OS X, etc.)
216
211
217 For RPM based systems, simply install the supplied package in the usual
212 For RPM based systems, simply install the supplied package in the usual
218 manner. If you download the tar archive, the process is:
213 manner. If you download the tar archive, the process is:
219
214
220 1. Unzip/untar the ipython-XXX.tar.gz file wherever you want (XXX is
215 1. Unzip/untar the ipython-XXX.tar.gz file wherever you want (XXX is
221 the version number). It will make a directory called ipython-XXX.
216 the version number). It will make a directory called ipython-XXX.
222 Change into that directory where you will find the files README
217 Change into that directory where you will find the files README
223 and setup.py. Once you've completed the installation, you can
218 and setup.py. Once you've completed the installation, you can
224 safely remove this directory.
219 safely remove this directory.
225 2. If you are installing over a previous installation of version
220 2. If you are installing over a previous installation of version
226 0.2.0 or earlier, first remove your $HOME/.ipython directory,
221 0.2.0 or earlier, first remove your $HOME/.ipython directory,
227 since the configuration file format has changed somewhat (the '='
222 since the configuration file format has changed somewhat (the '='
228 were removed from all option specifications). Or you can call
223 were removed from all option specifications). Or you can call
229 ipython with the -upgrade option and it will do this automatically
224 ipython with the -upgrade option and it will do this automatically
230 for you.
225 for you.
231 3. IPython uses distutils, so you can install it by simply typing at
226 3. IPython uses distutils, so you can install it by simply typing at
232 the system prompt (don't type the $)::
227 the system prompt (don't type the $)::
233
228
234 $ python setup.py install
229 $ python setup.py install
235
230
236 Note that this assumes you have root access to your machine. If
231 Note that this assumes you have root access to your machine. If
237 you don't have root access or don't want IPython to go in the
232 you don't have root access or don't want IPython to go in the
238 default python directories, you'll need to use the ``--home`` option
233 default python directories, you'll need to use the ``--home`` option
239 (or ``--prefix``). For example::
234 (or ``--prefix``). For example::
240
235
241 $ python setup.py install --home $HOME/local
236 $ python setup.py install --home $HOME/local
242
237
243 will install IPython into $HOME/local and its subdirectories
238 will install IPython into $HOME/local and its subdirectories
244 (creating them if necessary).
239 (creating them if necessary).
245 You can type::
240 You can type::
246
241
247 $ python setup.py --help
242 $ python setup.py --help
248
243
249 for more details.
244 for more details.
250
245
251 Note that if you change the default location for ``--home`` at
246 Note that if you change the default location for ``--home`` at
252 installation, IPython may end up installed at a location which is
247 installation, IPython may end up installed at a location which is
253 not part of your $PYTHONPATH environment variable. In this case,
248 not part of your $PYTHONPATH environment variable. In this case,
254 you'll need to configure this variable to include the actual
249 you'll need to configure this variable to include the actual
255 directory where the IPython/ directory ended (typically the value
250 directory where the IPython/ directory ended (typically the value
256 you give to ``--home`` plus /lib/python).
251 you give to ``--home`` plus /lib/python).
257
252
258
253
259 Mac OSX information
254 Mac OSX information
260 -------------------
255 -------------------
261
256
262 Under OSX, there is a choice you need to make. Apple ships its own build
257 Under OSX, there is a choice you need to make. Apple ships its own build
263 of Python, which lives in the core OSX filesystem hierarchy. You can
258 of Python, which lives in the core OSX filesystem hierarchy. You can
264 also manually install a separate Python, either purely by hand
259 also manually install a separate Python, either purely by hand
265 (typically in /usr/local) or by using Fink, which puts everything under
260 (typically in /usr/local) or by using Fink, which puts everything under
266 /sw. Which route to follow is a matter of personal preference, as I've
261 /sw. Which route to follow is a matter of personal preference, as I've
267 seen users who favor each of the approaches. Here I will simply list the
262 seen users who favor each of the approaches. Here I will simply list the
268 known installation issues under OSX, along with their solutions.
263 known installation issues under OSX, along with their solutions.
269
264
270 This page: http://geosci.uchicago.edu/~tobis/pylab.html contains
265 This page: http://geosci.uchicago.edu/~tobis/pylab.html contains
271 information on this topic, with additional details on how to make
266 information on this topic, with additional details on how to make
272 IPython and matplotlib play nicely under OSX.
267 IPython and matplotlib play nicely under OSX.
273
268
269 To run IPython and readline on OSX "Leopard" system python, see the
270 wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard
271
274
272
275 GUI problems
273 GUI problems
276 ------------
274 ------------
277
275
278 The following instructions apply to an install of IPython under OSX from
276 The following instructions apply to an install of IPython under OSX from
279 unpacking the .tar.gz distribution and installing it for the default
277 unpacking the .tar.gz distribution and installing it for the default
280 Python interpreter shipped by Apple. If you are using a fink install,
278 Python interpreter shipped by Apple. If you are using a fink install,
281 fink will take care of these details for you, by installing IPython
279 fink will take care of these details for you, by installing IPython
282 against fink's Python.
280 against fink's Python.
283
281
284 IPython offers various forms of support for interacting with graphical
282 IPython offers various forms of support for interacting with graphical
285 applications from the command line, from simple Tk apps (which are in
283 applications from the command line, from simple Tk apps (which are in
286 principle always supported by Python) to interactive control of WX, Qt
284 principle always supported by Python) to interactive control of WX, Qt
287 and GTK apps. Under OSX, however, this requires that ipython is
285 and GTK apps. Under OSX, however, this requires that ipython is
288 installed by calling the special pythonw script at installation time,
286 installed by calling the special pythonw script at installation time,
289 which takes care of coordinating things with Apple's graphical environment.
287 which takes care of coordinating things with Apple's graphical environment.
290
288
291 So when installing under OSX, it is best to use the following command::
289 So when installing under OSX, it is best to use the following command::
292
290
293 $ sudo pythonw setup.py install --install-scripts=/usr/local/bin
291 $ sudo pythonw setup.py install --install-scripts=/usr/local/bin
294
292
295 or
293 or
296
294
297 $ sudo pythonw setup.py install --install-scripts=/usr/bin
295 $ sudo pythonw setup.py install --install-scripts=/usr/bin
298
296
299 depending on where you like to keep hand-installed executables.
297 depending on where you like to keep hand-installed executables.
300
298
301 The resulting script will have an appropriate shebang line (the first
299 The resulting script will have an appropriate shebang line (the first
302 line in the script whic begins with #!...) such that the ipython
300 line in the script whic begins with #!...) such that the ipython
303 interpreter can interact with the OS X GUI. If the installed version
301 interpreter can interact with the OS X GUI. If the installed version
304 does not work and has a shebang line that points to, for example, just
302 does not work and has a shebang line that points to, for example, just
305 /usr/bin/python, then you might have a stale, cached version in your
303 /usr/bin/python, then you might have a stale, cached version in your
306 build/scripts-<python-version> directory. Delete that directory and
304 build/scripts-<python-version> directory. Delete that directory and
307 rerun the setup.py.
305 rerun the setup.py.
308
306
309 It is also a good idea to use the special flag ``--install-scripts`` as
307 It is also a good idea to use the special flag ``--install-scripts`` as
310 indicated above, to ensure that the ipython scripts end up in a location
308 indicated above, to ensure that the ipython scripts end up in a location
311 which is part of your $PATH. Otherwise Apple's Python will put the
309 which is part of your $PATH. Otherwise Apple's Python will put the
312 scripts in an internal directory not available by default at the command
310 scripts in an internal directory not available by default at the command
313 line (if you use /usr/local/bin, you need to make sure this is in your
311 line (if you use /usr/local/bin, you need to make sure this is in your
314 $PATH, which may not be true by default).
312 $PATH, which may not be true by default).
315
313
316
314
317 Readline problems
315 Readline problems
318 -----------------
316 -----------------
319
317
320 By default, the Python version shipped by Apple does not include the
318 By default, the Python version shipped by Apple does not include the
321 readline library, so central to IPython's behavior. If you install
319 readline library, so central to IPython's behavior. If you install
322 IPython against Apple's Python, you will not have arrow keys, tab
320 IPython against Apple's Python, you will not have arrow keys, tab
323 completion, etc. For Mac OSX 10.3 (Panther), you can find a prebuilt
321 completion, etc. For Mac OSX 10.3 (Panther), you can find a prebuilt
324 readline library here:
322 readline library here:
325 http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip
323 http://pythonmac.org/packages/readline-5.0-py2.3-macosx10.3.zip
326
324
327 If you are using OSX 10.4 (Tiger), after installing this package you
325 If you are using OSX 10.4 (Tiger), after installing this package you
328 need to either:
326 need to either:
329
327
330 1. move readline.so from /Library/Python/2.3 to
328 1. move readline.so from /Library/Python/2.3 to
331 /Library/Python/2.3/site-packages, or
329 /Library/Python/2.3/site-packages, or
332 2. install http://pythonmac.org/packages/TigerPython23Compat.pkg.zip
330 2. install http://pythonmac.org/packages/TigerPython23Compat.pkg.zip
333
331
334 Users installing against Fink's Python or a properly hand-built one
332 Users installing against Fink's Python or a properly hand-built one
335 should not have this problem.
333 should not have this problem.
336
334
337
335
338 DarwinPorts
336 DarwinPorts
339 -----------
337 -----------
340
338
341 I report here a message from an OSX user, who suggests an alternative
339 I report here a message from an OSX user, who suggests an alternative
342 means of using IPython under this operating system with good results.
340 means of using IPython under this operating system with good results.
343 Please let me know of any updates that may be useful for this section.
341 Please let me know of any updates that may be useful for this section.
344 His message is reproduced verbatim below:
342 His message is reproduced verbatim below:
345
343
346 From: Markus Banfi <markus.banfi-AT-mospheira.net>
344 From: Markus Banfi <markus.banfi-AT-mospheira.net>
347
345
348 As a MacOS X (10.4.2) user I prefer to install software using
346 As a MacOS X (10.4.2) user I prefer to install software using
349 DawinPorts instead of Fink. I had no problems installing ipython
347 DawinPorts instead of Fink. I had no problems installing ipython
350 with DarwinPorts. It's just:
348 with DarwinPorts. It's just:
351
349
352 sudo port install py-ipython
350 sudo port install py-ipython
353
351
354 It automatically resolved all dependencies (python24, readline,
352 It automatically resolved all dependencies (python24, readline,
355 py-readline). So far I did not encounter any problems with the
353 py-readline). So far I did not encounter any problems with the
356 DarwinPorts port of ipython.
354 DarwinPorts port of ipython.
357
355
358
356
359
357
360 Windows instructions
358 Windows instructions
361 --------------------
359 --------------------
362
360
363 Some of IPython's very useful features are:
361 Some of IPython's very useful features are:
364
362
365 * Integrated readline support (Tab-based file, object and attribute
363 * Integrated readline support (Tab-based file, object and attribute
366 completion, input history across sessions, editable command line,
364 completion, input history across sessions, editable command line,
367 etc.)
365 etc.)
368 * Coloring of prompts, code and tracebacks.
366 * Coloring of prompts, code and tracebacks.
369
367
368 .. _pyreadline:
369
370 These, by default, are only available under Unix-like operating systems.
370 These, by default, are only available under Unix-like operating systems.
371 However, thanks to Gary Bishop's work, Windows XP/2k users can also
371 However, thanks to Gary Bishop's work, Windows XP/2k users can also
372 benefit from them. His readline library originally implemented both GNU
372 benefit from them. His readline library originally implemented both GNU
373 readline functionality and color support, so that IPython under Windows
373 readline functionality and color support, so that IPython under Windows
374 XP/2k can be as friendly and powerful as under Unix-like environments.
374 XP/2k can be as friendly and powerful as under Unix-like environments.
375
375
376 This library, now named PyReadline, has been absorbed by the IPython
376 This library, now named PyReadline, has been absorbed by the IPython
377 team (Jörgen Stenarson, in particular), and it continues to be developed
377 team (Jörgen Stenarson, in particular), and it continues to be developed
378 with new features, as well as being distributed directly from the
378 with new features, as well as being distributed directly from the
379 IPython site.
379 IPython site.
380
380
381 The PyReadline extension requires CTypes and the windows IPython
381 The PyReadline extension requires CTypes and the windows IPython
382 installer needs PyWin32, so in all you need:
382 installer needs PyWin32, so in all you need:
383
383
384 1. PyWin32 from http://sourceforge.net/projects/pywin32.
384 1. PyWin32 from http://sourceforge.net/projects/pywin32.
385 2. PyReadline for Windows from
385 2. PyReadline for Windows from
386 http://ipython.scipy.org/moin/PyReadline/Intro. That page contains
386 http://ipython.scipy.org/moin/PyReadline/Intro. That page contains
387 further details on using and configuring the system to your liking.
387 further details on using and configuring the system to your liking.
388 3. Finally, only if you are using Python 2.3 or 2.4, you need CTypes
388 3. Finally, only if you are using Python 2.3 or 2.4, you need CTypes
389 from http://starship.python.net/crew/theller/ctypes(you must use
389 from http://starship.python.net/crew/theller/ctypes(you must use
390 version 0.9.1 or newer). This package is included in Python 2.5,
390 version 0.9.1 or newer). This package is included in Python 2.5,
391 so you don't need to manually get it if your Python version is 2.5
391 so you don't need to manually get it if your Python version is 2.5
392 or newer.
392 or newer.
393
393
394 Warning about a broken readline-like library: several users have
394 Warning about a broken readline-like library: several users have
395 reported problems stemming from using the pseudo-readline library at
395 reported problems stemming from using the pseudo-readline library at
396 http://newcenturycomputers.net/projects/readline.html. This is a broken
396 http://newcenturycomputers.net/projects/readline.html. This is a broken
397 library which, while called readline, only implements an incomplete
397 library which, while called readline, only implements an incomplete
398 subset of the readline API. Since it is still called readline, it fools
398 subset of the readline API. Since it is still called readline, it fools
399 IPython's detection mechanisms and causes unpredictable crashes later.
399 IPython's detection mechanisms and causes unpredictable crashes later.
400 If you wish to use IPython under Windows, you must NOT use this library,
400 If you wish to use IPython under Windows, you must NOT use this library,
401 which for all purposes is (at least as of version 1.6) terminally broken.
401 which for all purposes is (at least as of version 1.6) terminally broken.
402
402
403
403
404 Installation procedure
404 Installation procedure
405 ----------------------
405 ----------------------
406
406
407 Once you have the above installed, from the IPython download directory
407 Once you have the above installed, from the IPython download directory
408 grab the ipython-XXX.win32.exe file, where XXX represents the version
408 grab the ipython-XXX.win32.exe file, where XXX represents the version
409 number. This is a regular windows executable installer, which you can
409 number. This is a regular windows executable installer, which you can
410 simply double-click to install. It will add an entry for IPython to your
410 simply double-click to install. It will add an entry for IPython to your
411 Start Menu, as well as registering IPython in the Windows list of
411 Start Menu, as well as registering IPython in the Windows list of
412 applications, so you can later uninstall it from the Control Panel.
412 applications, so you can later uninstall it from the Control Panel.
413
413
414 IPython tries to install the configuration information in a directory
414 IPython tries to install the configuration information in a directory
415 named .ipython (_ipython under Windows) located in your 'home'
415 named .ipython (_ipython under Windows) located in your 'home'
416 directory. IPython sets this directory by looking for a HOME environment
416 directory. IPython sets this directory by looking for a HOME environment
417 variable; if such a variable does not exist, it uses HOMEDRIVE\HOMEPATH
417 variable; if such a variable does not exist, it uses HOMEDRIVE\HOMEPATH
418 (these are always defined by Windows). This typically gives something
418 (these are always defined by Windows). This typically gives something
419 like C:\Documents and Settings\YourUserName, but your local details may
419 like C:\Documents and Settings\YourUserName, but your local details may
420 vary. In this directory you will find all the files that configure
420 vary. In this directory you will find all the files that configure
421 IPython's defaults, and you can put there your profiles and extensions.
421 IPython's defaults, and you can put there your profiles and extensions.
422 This directory is automatically added by IPython to sys.path, so
422 This directory is automatically added by IPython to sys.path, so
423 anything you place there can be found by import statements.
423 anything you place there can be found by import statements.
424
424
425
425
426 Upgrading
426 Upgrading
427 ---------
427 ---------
428
428
429 For an IPython upgrade, you should first uninstall the previous version.
429 For an IPython upgrade, you should first uninstall the previous version.
430 This will ensure that all files and directories (such as the
430 This will ensure that all files and directories (such as the
431 documentation) which carry embedded version strings in their names are
431 documentation) which carry embedded version strings in their names are
432 properly removed.
432 properly removed.
433
433
434
434
435 Manual installation under Win32
435 Manual installation under Win32
436 -------------------------------
436 -------------------------------
437
437
438 In case the automatic installer does not work for some reason, you can
438 In case the automatic installer does not work for some reason, you can
439 download the ipython-XXX.tar.gz file, which contains the full IPython
439 download the ipython-XXX.tar.gz file, which contains the full IPython
440 source distribution (the popular WinZip can read .tar.gz files). After
440 source distribution (the popular WinZip can read .tar.gz files). After
441 uncompressing the archive, you can install it at a command terminal just
441 uncompressing the archive, you can install it at a command terminal just
442 like any other Python module, by using 'python setup.py install'.
442 like any other Python module, by using 'python setup.py install'.
443
443
444 After the installation, run the supplied win32_manual_post_install.py
444 After the installation, run the supplied win32_manual_post_install.py
445 script, which creates the necessary Start Menu shortcuts for you.
445 script, which creates the necessary Start Menu shortcuts for you.
446
446
447
447
448 .. upgrading:
448
449
449 Upgrading from a previous version
450 Upgrading from a previous version
450 ---------------------------------
451 ---------------------------------
451
452
452 If you are upgrading from a previous version of IPython, after doing the
453 If you are upgrading from a previous version of IPython, you may want
453 routine installation described above, you should call IPython with the
454 to upgrade the contents of your ~/.ipython directory. Just run
454 -upgrade option the first time you run your new copy. This will
455 %upgrade, look at the diffs and delete the suggested files manually,
455 automatically update your configuration directory while preserving
456 if you think you can lose the old versions. %upgrade will never
456 copies of your old files. You can then later merge back any personal
457 overwrite or delete anything.
457 customizations you may have made into the new files. It is a good idea
458 to do this as there may be new options available in the new
459 configuration files which you will not have.
460
461 Under Windows, if you don't know how to call python scripts with
462 arguments from a command line, simply delete the old config directory
463 and IPython will make a new one. Win2k and WinXP users will find it in
464 C:\Documents and Settings\YourUserName\_ipython, and Win 9x users under
465 C:\Program Files\IPython\_ipython.
466
458
467 Initial configuration of your environment
459 Initial configuration of your environment
468 =========================================
460 =========================================
469
461
470 This section will help you set various things in your environment for
462 This section will help you set various things in your environment for
471 your IPython sessions to be as efficient as possible. All of IPython's
463 your IPython sessions to be as efficient as possible. All of IPython's
472 configuration information, along with several example files, is stored
464 configuration information, along with several example files, is stored
473 in a directory named by default $HOME/.ipython. You can change this by
465 in a directory named by default $HOME/.ipython. You can change this by
474 defining the environment variable IPYTHONDIR, or at runtime with the
466 defining the environment variable IPYTHONDIR, or at runtime with the
475 command line option -ipythondir.
467 command line option -ipythondir.
476
468
477 If all goes well, the first time you run IPython it should automatically
469 If all goes well, the first time you run IPython it should
478 create a user copy of the config directory for you, based on its builtin
470 automatically create a user copy of the config directory for you,
479 defaults. You can look at the files it creates to learn more about
471 based on its builtin defaults. You can look at the files it creates to
480 configuring the system. The main file you will modify to configure
472 learn more about configuring the system. The main file you will modify
481 IPython's behavior is called ipythonrc (with a .ini extension under
473 to configure IPython's behavior is called ipythonrc (with a .ini
482 Windows), included for reference in Sec. 7.1
474 extension under Windows), included for reference in `ipythonrc`_
483 <node7.html#sec:ipytonrc-sample>. This file is very commented and has
475 section. This file is very commented and has many variables you can
484 many variables you can change to suit your taste, you can find more
476 change to suit your taste, you can find more details in
485 details in Sec. 7 <node7.html#sec:customization>. Here we discuss the
477 Sec. customization_. Here we discuss the basic things you will want to
486 basic things you will want to make sure things are working properly from
478 make sure things are working properly from the beginning.
487 the beginning.
488
479
489
480
481 .. _Accessing help:
490
482
491 Access to the Python help system
483 Access to the Python help system
492 --------------------------------
484 --------------------------------
493
485
494 This is true for Python in general (not just for IPython): you should
486 This is true for Python in general (not just for IPython): you should
495 have an environment variable called PYTHONDOCS pointing to the directory
487 have an environment variable called PYTHONDOCS pointing to the directory
496 where your HTML Python documentation lives. In my system it's
488 where your HTML Python documentation lives. In my system it's
497 /usr/share/doc/python-docs-2.3.4/html, check your local details or ask
489 /usr/share/doc/python-docs-2.3.4/html, check your local details or ask
498 your systems administrator.
490 your systems administrator.
499
491
500 This is the directory which holds the HTML version of the Python
492 This is the directory which holds the HTML version of the Python
501 manuals. Unfortunately it seems that different Linux distributions
493 manuals. Unfortunately it seems that different Linux distributions
502 package these files differently, so you may have to look around a bit.
494 package these files differently, so you may have to look around a bit.
503 Below I show the contents of this directory on my system for reference::
495 Below I show the contents of this directory on my system for reference::
504
496
505 [html]> ls
497 [html]> ls
506 about.dat acks.html dist/ ext/ index.html lib/ modindex.html
498 about.dat acks.html dist/ ext/ index.html lib/ modindex.html
507 stdabout.dat tut/ about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
499 stdabout.dat tut/ about.html api/ doc/ icons/ inst/ mac/ ref/ style.css
508
500
509 You should really make sure this variable is correctly set so that
501 You should really make sure this variable is correctly set so that
510 Python's pydoc-based help system works. It is a powerful and convenient
502 Python's pydoc-based help system works. It is a powerful and convenient
511 system with full access to the Python manuals and all modules accessible
503 system with full access to the Python manuals and all modules accessible
512 to you.
504 to you.
513
505
514 Under Windows it seems that pydoc finds the documentation automatically,
506 Under Windows it seems that pydoc finds the documentation automatically,
515 so no extra setup appears necessary.
507 so no extra setup appears necessary.
516
508
517
509
518 Editor
510 Editor
519 ------
511 ------
520
512
521 The %edit command (and its alias %ed) will invoke the editor set in your
513 The %edit command (and its alias %ed) will invoke the editor set in your
522 environment as EDITOR. If this variable is not set, it will default to
514 environment as EDITOR. If this variable is not set, it will default to
523 vi under Linux/Unix and to notepad under Windows. You may want to set
515 vi under Linux/Unix and to notepad under Windows. You may want to set
524 this variable properly and to a lightweight editor which doesn't take
516 this variable properly and to a lightweight editor which doesn't take
525 too long to start (that is, something other than a new instance of
517 too long to start (that is, something other than a new instance of
526 Emacs). This way you can edit multi-line code quickly and with the power
518 Emacs). This way you can edit multi-line code quickly and with the power
527 of a real editor right inside IPython.
519 of a real editor right inside IPython.
528
520
529 If you are a dedicated Emacs user, you should set up the Emacs server so
521 If you are a dedicated Emacs user, you should set up the Emacs server so
530 that new requests are handled by the original process. This means that
522 that new requests are handled by the original process. This means that
531 almost no time is spent in handling the request (assuming an Emacs
523 almost no time is spent in handling the request (assuming an Emacs
532 process is already running). For this to work, you need to set your
524 process is already running). For this to work, you need to set your
533 EDITOR environment variable to 'emacsclient'. The code below, supplied
525 EDITOR environment variable to 'emacsclient'. The code below, supplied
534 by Francois Pinard, can then be used in your .emacs file to enable the
526 by Francois Pinard, can then be used in your .emacs file to enable the
535 server::
527 server::
536
528
537 (defvar server-buffer-clients)
529 (defvar server-buffer-clients)
538 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
530 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
539 (server-start)
531 (server-start)
540 (defun fp-kill-server-with-buffer-routine ()
532 (defun fp-kill-server-with-buffer-routine ()
541 (and server-buffer-clients (server-done)))
533 (and server-buffer-clients (server-done)))
542 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
534 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
543
535
544 You can also set the value of this editor via the commmand-line option
536 You can also set the value of this editor via the commmand-line option
545 '-editor' or in your ipythonrc file. This is useful if you wish to use
537 '-editor' or in your ipythonrc file. This is useful if you wish to use
546 specifically for IPython an editor different from your typical default
538 specifically for IPython an editor different from your typical default
547 (and for Windows users who tend to use fewer environment variables).
539 (and for Windows users who tend to use fewer environment variables).
548
540
549
541
550 Color
542 Color
551 -----
543 -----
552
544
553 The default IPython configuration has most bells and whistles turned on
545 The default IPython configuration has most bells and whistles turned on
554 (they're pretty safe). But there's one that may cause problems on some
546 (they're pretty safe). But there's one that may cause problems on some
555 systems: the use of color on screen for displaying information. This is
547 systems: the use of color on screen for displaying information. This is
556 very useful, since IPython can show prompts and exception tracebacks
548 very useful, since IPython can show prompts and exception tracebacks
557 with various colors, display syntax-highlighted source code, and in
549 with various colors, display syntax-highlighted source code, and in
558 general make it easier to visually parse information.
550 general make it easier to visually parse information.
559
551
560 The following terminals seem to handle the color sequences fine:
552 The following terminals seem to handle the color sequences fine:
561
553
562 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
554 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
563 rxvt, xterm.
555 rxvt, xterm.
564 * CDE terminal (tested under Solaris). This one boldfaces light colors.
556 * CDE terminal (tested under Solaris). This one boldfaces light colors.
565 * (X)Emacs buffers. See sec.3.4 <#sec:emacs> for more details on
557 * (X)Emacs buffers. See the emacs_ section for more details on
566 using IPython with (X)Emacs.
558 using IPython with (X)Emacs.
567 * A Windows (XP/2k) command prompt with Gary Bishop's support
559 * A Windows (XP/2k) command prompt with pyreadline_.
568 extensions. Gary's extensions are discussed in Sec. 2.3
569 <node2.html#sub:Under-Windows>.
570 * A Windows (XP/2k) CygWin shell. Although some users have reported
560 * A Windows (XP/2k) CygWin shell. Although some users have reported
571 problems; it is not clear whether there is an issue for everyone
561 problems; it is not clear whether there is an issue for everyone
572 or only under specific configurations. If you have full color
562 or only under specific configurations. If you have full color
573 support under cygwin, please post to the IPython mailing list so
563 support under cygwin, please post to the IPython mailing list so
574 this issue can be resolved for all users.
564 this issue can be resolved for all users.
575
565
576 These have shown problems:
566 These have shown problems:
577
567
578 * Windows command prompt in WinXP/2k logged into a Linux machine via
568 * Windows command prompt in WinXP/2k logged into a Linux machine via
579 telnet or ssh.
569 telnet or ssh.
580 * Windows native command prompt in WinXP/2k, without Gary Bishop's
570 * Windows native command prompt in WinXP/2k, without Gary Bishop's
581 extensions. Once Gary's readline library is installed, the normal
571 extensions. Once Gary's readline library is installed, the normal
582 WinXP/2k command prompt works perfectly.
572 WinXP/2k command prompt works perfectly.
583
573
584 Currently the following color schemes are available:
574 Currently the following color schemes are available:
585
575
586 * NoColor: uses no color escapes at all (all escapes are empty '' ''
576 * NoColor: uses no color escapes at all (all escapes are empty '' ''
587 strings). This 'scheme' is thus fully safe to use in any terminal.
577 strings). This 'scheme' is thus fully safe to use in any terminal.
588 * Linux: works well in Linux console type environments: dark
578 * Linux: works well in Linux console type environments: dark
589 background with light fonts. It uses bright colors for
579 background with light fonts. It uses bright colors for
590 information, so it is difficult to read if you have a light
580 information, so it is difficult to read if you have a light
591 colored background.
581 colored background.
592 * LightBG: the basic colors are similar to those in the Linux scheme
582 * LightBG: the basic colors are similar to those in the Linux scheme
593 but darker. It is easy to read in terminals with light backgrounds.
583 but darker. It is easy to read in terminals with light backgrounds.
594
584
595 IPython uses colors for two main groups of things: prompts and
585 IPython uses colors for two main groups of things: prompts and
596 tracebacks which are directly printed to the terminal, and the object
586 tracebacks which are directly printed to the terminal, and the object
597 introspection system which passes large sets of data through a pager.
587 introspection system which passes large sets of data through a pager.
598
588
599
589
600 Input/Output prompts and exception tracebacks
590 Input/Output prompts and exception tracebacks
601 ---------------------------------------------
591 ---------------------------------------------
602
592
603 You can test whether the colored prompts and tracebacks work on your
593 You can test whether the colored prompts and tracebacks work on your
604 system interactively by typing '%colors Linux' at the prompt (use
594 system interactively by typing '%colors Linux' at the prompt (use
605 '%colors LightBG' if your terminal has a light background). If the input
595 '%colors LightBG' if your terminal has a light background). If the input
606 prompt shows garbage like::
596 prompt shows garbage like::
607
597
608 [0;32mIn [[1;32m1[0;32m]: [0;00m
598 [0;32mIn [[1;32m1[0;32m]: [0;00m
609
599
610 instead of (in color) something like::
600 instead of (in color) something like::
611
601
612 In [1]:
602 In [1]:
613
603
614 this means that your terminal doesn't properly handle color escape
604 this means that your terminal doesn't properly handle color escape
615 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
605 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
616
606
617 You can try using a different terminal emulator program (Emacs users,
607 You can try using a different terminal emulator program (Emacs users,
618 see below). To permanently set your color preferences, edit the file
608 see below). To permanently set your color preferences, edit the file
619 $HOME/.ipython/ipythonrc and set the colors option to the desired value.
609 $HOME/.ipython/ipythonrc and set the colors option to the desired value.
620
610
621
611
622 Object details (types, docstrings, source code, etc.)
612 Object details (types, docstrings, source code, etc.)
623 -----------------------------------------------------
613 -----------------------------------------------------
624
614
625 IPython has a set of special functions for studying the objects you are
615 IPython has a set of special functions for studying the objects you
626 working with, discussed in detail in Sec. 6.4
616 are working with, discussed in detail in Sec. `dynamic object
627 <node6.html#sec:dyn-object-info>. But this system relies on passing
617 information`_. But this system relies on passing information which is
628 information which is longer than your screen through a data pager, such
618 longer than your screen through a data pager, such as the common Unix
629 as the common Unix less and more programs. In order to be able to see
619 less and more programs. In order to be able to see this information in
630 this information in color, your pager needs to be properly configured. I
620 color, your pager needs to be properly configured. I strongly
631 strongly recommend using less instead of more, as it seems that more
621 recommend using less instead of more, as it seems that more simply can
632 simply can not understand colored text correctly.
622 not understand colored text correctly.
633
623
634 In order to configure less as your default pager, do the following:
624 In order to configure less as your default pager, do the following:
635
625
636 1. Set the environment PAGER variable to less.
626 1. Set the environment PAGER variable to less.
637 2. Set the environment LESS variable to -r (plus any other options
627 2. Set the environment LESS variable to -r (plus any other options
638 you always want to pass to less by default). This tells less to
628 you always want to pass to less by default). This tells less to
639 properly interpret control sequences, which is how color
629 properly interpret control sequences, which is how color
640 information is given to your terminal.
630 information is given to your terminal.
641
631
642 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
632 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
643
633
644 setenv PAGER less
634 setenv PAGER less
645 setenv LESS -r
635 setenv LESS -r
646
636
647 There is similar syntax for other Unix shells, look at your system
637 There is similar syntax for other Unix shells, look at your system
648 documentation for details.
638 documentation for details.
649
639
650 If you are on a system which lacks proper data pagers (such as Windows),
640 If you are on a system which lacks proper data pagers (such as Windows),
651 IPython will use a very limited builtin pager.
641 IPython will use a very limited builtin pager.
652
642
643 .. _emacs:
644
653 (X)Emacs configuration
645 (X)Emacs configuration
654 ----------------------
646 ----------------------
655
647
656 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
648 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
657 currently (X)Emacs and IPython get along very well.
649 currently (X)Emacs and IPython get along very well.
658
650
659 Important note: You will need to use a recent enough version of
651 Important note: You will need to use a recent enough version of
660 python-mode.el, along with the file ipython.el. You can check that the
652 python-mode.el, along with the file ipython.el. You can check that the
661 version you have of python-mode.el is new enough by either looking at
653 version you have of python-mode.el is new enough by either looking at
662 the revision number in the file itself, or asking for it in (X)Emacs via
654 the revision number in the file itself, or asking for it in (X)Emacs via
663 M-x py-version. Versions 4.68 and newer contain the necessary fixes for
655 M-x py-version. Versions 4.68 and newer contain the necessary fixes for
664 proper IPython support.
656 proper IPython support.
665
657
666 The file ipython.el is included with the IPython distribution, in the
658 The file ipython.el is included with the IPython distribution, in the
667 documentation directory (where this manual resides in PDF and HTML
659 documentation directory (where this manual resides in PDF and HTML
668 formats).
660 formats).
669
661
670 Once you put these files in your Emacs path, all you need in your .emacs
662 Once you put these files in your Emacs path, all you need in your .emacs
671 file is::
663 file is::
672
664
673 (require 'ipython)
665 (require 'ipython)
674
666
675 This should give you full support for executing code snippets via
667 This should give you full support for executing code snippets via
676 IPython, opening IPython as your Python shell via C-c !, etc.
668 IPython, opening IPython as your Python shell via C-c !, etc.
677
669
678 If you happen to get garbage instead of colored prompts as described in
670 If you happen to get garbage instead of colored prompts as described in
679 the previous section, you may need to set also in your .emacs file::
671 the previous section, you may need to set also in your .emacs file::
680
672
681 (setq ansi-color-for-comint-mode t)
673 (setq ansi-color-for-comint-mode t)
682
674
683
675
684 Notes:
676 Notes:
685
677
686 * There is one caveat you should be aware of: you must start the
678 * There is one caveat you should be aware of: you must start the
687 IPython shell before attempting to execute any code regions via
679 IPython shell before attempting to execute any code regions via
688 ``C-c |``. Simply type C-c ! to start IPython before passing any code
680 ``C-c |``. Simply type C-c ! to start IPython before passing any code
689 regions to the interpreter, and you shouldn't experience any
681 regions to the interpreter, and you shouldn't experience any
690 problems.
682 problems.
691 This is due to a bug in Python itself, which has been fixed for
683 This is due to a bug in Python itself, which has been fixed for
692 Python 2.3, but exists as of Python 2.2.2 (reported as SF bug [
684 Python 2.3, but exists as of Python 2.2.2 (reported as SF bug [
693 737947 ]).
685 737947 ]).
694 * The (X)Emacs support is maintained by Alexander Schmolck, so all
686 * The (X)Emacs support is maintained by Alexander Schmolck, so all
695 comments/requests should be directed to him through the IPython
687 comments/requests should be directed to him through the IPython
696 mailing lists.
688 mailing lists.
697 * This code is still somewhat experimental so it's a bit rough
689 * This code is still somewhat experimental so it's a bit rough
698 around the edges (although in practice, it works quite well).
690 around the edges (although in practice, it works quite well).
699 * Be aware that if you customize py-python-command previously, this
691 * Be aware that if you customize py-python-command previously, this
700 value will override what ipython.el does (because loading the
692 value will override what ipython.el does (because loading the
701 customization variables comes later).
693 customization variables comes later).
702
694
695 .. Quick tips:
696
703 Quick tips
697 Quick tips
704 ==========
698 ==========
705
699
706 IPython can be used as an improved replacement for the Python prompt,
700 IPython can be used as an improved replacement for the Python prompt,
707 and for that you don't really need to read any more of this manual. But
701 and for that you don't really need to read any more of this manual. But
708 in this section we'll try to summarize a few tips on how to make the
702 in this section we'll try to summarize a few tips on how to make the
709 most effective use of it for everyday Python development, highlighting
703 most effective use of it for everyday Python development, highlighting
710 things you might miss in the rest of the manual (which is getting long).
704 things you might miss in the rest of the manual (which is getting long).
711 We'll give references to parts in the manual which provide more detail
705 We'll give references to parts in the manual which provide more detail
712 when appropriate.
706 when appropriate.
713
707
714 The following article by Jeremy Jones provides an introductory tutorial
708 The following article by Jeremy Jones provides an introductory tutorial
715 about IPython:
709 about IPython:
716 http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
710 http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
717
711
718 * The TAB key. TAB-completion, especially for attributes, is a
712 * The TAB key. TAB-completion, especially for attributes, is a
719 convenient way to explore the structure of any object you're
713 convenient way to explore the structure of any object you're
720 dealing with. Simply type object_name.<TAB> and a list of the
714 dealing with. Simply type object_name.<TAB> and a list of the
721 object's attributes will be printed (see sec. 6.5
715 object's attributes will be printed (see readline_ for
722 <node6.html#sec:readline> for more). Tab completion also works on
716 more). Tab completion also works on
723 file and directory names, which combined with IPython's alias
717 file and directory names, which combined with IPython's alias
724 system allows you to do from within IPython many of the things you
718 system allows you to do from within IPython many of the things you
725 normally would need the system shell for.
719 normally would need the system shell for.
726 * Explore your objects. Typing object_name? will print all sorts of
720 * Explore your objects. Typing object_name? will print all sorts of
727 details about any object, including docstrings, function
721 details about any object, including docstrings, function
728 definition lines (for call arguments) and constructor details for
722 definition lines (for call arguments) and constructor details for
729 classes. The magic commands %pdoc, %pdef, %psource and %pfile will
723 classes. The magic commands %pdoc, %pdef, %psource and %pfile will
730 respectively print the docstring, function definition line, full
724 respectively print the docstring, function definition line, full
731 source code and the complete file for any object (when they can be
725 source code and the complete file for any object (when they can be
732 found). If automagic is on (it is by default), you don't need to
726 found). If automagic is on (it is by default), you don't need to
733 type the '%' explicitly. See sec. 6.4
727 type the '%' explicitly. See sec. `dynamic object information`_
734 <node6.html#sec:dyn-object-info> for more.
728 for more.
735 * The %run magic command allows you to run any python script and
729 * The %run magic command allows you to run any python script and
736 load all of its data directly into the interactive namespace.
730 load all of its data directly into the interactive namespace.
737 Since the file is re-read from disk each time, changes you make to
731 Since the file is re-read from disk each time, changes you make to
738 it are reflected immediately (in contrast to the behavior of
732 it are reflected immediately (in contrast to the behavior of
739 import). I rarely use import for code I am testing, relying on
733 import). I rarely use import for code I am testing, relying on
740 %run instead. See sec. 6.2 <node6.html#sec:magic> for more on this
734 %run instead. See magic_ section for more on this
741 and other magic commands, or type the name of any magic command
735 and other magic commands, or type the name of any magic command
742 and ? to get details on it. See also sec. 6.9
736 and ? to get details on it. See also sec. dreload_ for a
743 <node6.html#sec:dreload> for a recursive reload command.
737 recursive reload command.
744 %run also has special flags for timing the execution of your
738 %run also has special flags for timing the execution of your
745 scripts (-t) and for executing them under the control of either
739 scripts (-t) and for executing them under the control of either
746 Python's pdb debugger (-d) or profiler (-p). With all of these,
740 Python's pdb debugger (-d) or profiler (-p). With all of these,
747 %run can be used as the main tool for efficient interactive
741 %run can be used as the main tool for efficient interactive
748 development of code which you write in your editor of choice.
742 development of code which you write in your editor of choice.
749 * Use the Python debugger, pdb^2 <footnode.html#foot360>. The %pdb
743 * Use the Python debugger, pdb. The %pdb
750 command allows you to toggle on and off the automatic invocation
744 command allows you to toggle on and off the automatic invocation
751 of an IPython-enhanced pdb debugger (with coloring, tab completion
745 of an IPython-enhanced pdb debugger (with coloring, tab completion
752 and more) at any uncaught exception. The advantage of this is that
746 and more) at any uncaught exception. The advantage of this is that
753 pdb starts inside the function where the exception occurred, with
747 pdb starts inside the function where the exception occurred, with
754 all data still available. You can print variables, see code,
748 all data still available. You can print variables, see code,
755 execute statements and even walk up and down the call stack to
749 execute statements and even walk up and down the call stack to
756 track down the true source of the problem (which often is many
750 track down the true source of the problem (which often is many
757 layers in the stack above where the exception gets triggered).
751 layers in the stack above where the exception gets triggered).
758 Running programs with %run and pdb active can be an efficient to
752 Running programs with %run and pdb active can be an efficient to
759 develop and debug code, in many cases eliminating the need for
753 develop and debug code, in many cases eliminating the need for
760 print statements or external debugging tools. I often simply put a
754 print statements or external debugging tools. I often simply put a
761 1/0 in a place where I want to take a look so that pdb gets
755 1/0 in a place where I want to take a look so that pdb gets
762 called, quickly view whatever variables I need to or test various
756 called, quickly view whatever variables I need to or test various
763 pieces of code and then remove the 1/0.
757 pieces of code and then remove the 1/0.
764 Note also that '%run -d' activates pdb and automatically sets
758 Note also that '%run -d' activates pdb and automatically sets
765 initial breakpoints for you to step through your code, watch
759 initial breakpoints for you to step through your code, watch
766 variables, etc. See Sec. 6.12 <node6.html#sec:cache_output> for
760 variables, etc. See Sec. `Output caching`_ for
767 details.
761 details.
768 * Use the output cache. All output results are automatically stored
762 * Use the output cache. All output results are automatically stored
769 in a global dictionary named Out and variables named _1, _2, etc.
763 in a global dictionary named Out and variables named _1, _2, etc.
770 alias them. For example, the result of input line 4 is available
764 alias them. For example, the result of input line 4 is available
771 either as Out[4] or as _4. Additionally, three variables named _,
765 either as Out[4] or as _4. Additionally, three variables named _,
772 __ and ___ are always kept updated with the for the last three
766 __ and ___ are always kept updated with the for the last three
773 results. This allows you to recall any previous result and further
767 results. This allows you to recall any previous result and further
774 use it for new calculations. See Sec. 6.12
768 use it for new calculations. See Sec. `Output caching`_ for more.
775 <node6.html#sec:cache_output> for more.
776 * Put a ';' at the end of a line to supress the printing of output.
769 * Put a ';' at the end of a line to supress the printing of output.
777 This is useful when doing calculations which generate long output
770 This is useful when doing calculations which generate long output
778 you are not interested in seeing. The _* variables and the Out[]
771 you are not interested in seeing. The _* variables and the Out[]
779 list do get updated with the contents of the output, even if it is
772 list do get updated with the contents of the output, even if it is
780 not printed. You can thus still access the generated results this
773 not printed. You can thus still access the generated results this
781 way for further processing.
774 way for further processing.
782 * A similar system exists for caching input. All input is stored in
775 * A similar system exists for caching input. All input is stored in
783 a global list called In , so you can re-execute lines 22 through
776 a global list called In , so you can re-execute lines 22 through
784 28 plus line 34 by typing 'exec In[22:29]+In[34]' (using Python
777 28 plus line 34 by typing 'exec In[22:29]+In[34]' (using Python
785 slicing notation). If you need to execute the same set of lines
778 slicing notation). If you need to execute the same set of lines
786 often, you can assign them to a macro with the %macro function.
779 often, you can assign them to a macro with the %macro function.
787 See sec. 6.11 <node6.html#sec:cache_input> for more.
780 See sec. `Input caching`_ for more.
788 * Use your input history. The %hist command can show you all
781 * Use your input history. The %hist command can show you all
789 previous input, without line numbers if desired (option -n) so you
782 previous input, without line numbers if desired (option -n) so you
790 can directly copy and paste code either back in IPython or in a
783 can directly copy and paste code either back in IPython or in a
791 text editor. You can also save all your history by turning on
784 text editor. You can also save all your history by turning on
792 logging via %logstart; these logs can later be either reloaded as
785 logging via %logstart; these logs can later be either reloaded as
793 IPython sessions or used as code for your programs.
786 IPython sessions or used as code for your programs.
794 * Define your own system aliases. Even though IPython gives you
787 * Define your own system aliases. Even though IPython gives you
795 access to your system shell via the ! prefix, it is convenient to
788 access to your system shell via the ! prefix, it is convenient to
796 have aliases to the system commands you use most often. This
789 have aliases to the system commands you use most often. This
797 allows you to work seamlessly from inside IPython with the same
790 allows you to work seamlessly from inside IPython with the same
798 commands you are used to in your system shell.
791 commands you are used to in your system shell.
799 IPython comes with some pre-defined aliases and a complete system
792 IPython comes with some pre-defined aliases and a complete system
800 for changing directories, both via a stack (see %pushd, %popd and
793 for changing directories, both via a stack (see %pushd, %popd and
801 %dhist) and via direct %cd. The latter keeps a history of visited
794 %dhist) and via direct %cd. The latter keeps a history of visited
802 directories and allows you to go to any previously visited one.
795 directories and allows you to go to any previously visited one.
803 * Use Python to manipulate the results of system commands. The '!!'
796 * Use Python to manipulate the results of system commands. The '!!'
804 special syntax, and the %sc and %sx magic commands allow you to
797 special syntax, and the %sc and %sx magic commands allow you to
805 capture system output into Python variables.
798 capture system output into Python variables.
806 * Expand python variables when calling the shell (either via '!' and
799 * Expand python variables when calling the shell (either via '!' and
807 '!!' or via aliases) by prepending a $ in front of them. You can
800 '!!' or via aliases) by prepending a $ in front of them. You can
808 also expand complete python expressions. See sec. 6.7
801 also expand complete python expressions. See
809 <node6.html#sub:System-shell-access> for more.
802 `System shell access`_ for more.
810 * Use profiles to maintain different configurations (modules to
803 * Use profiles to maintain different configurations (modules to
811 load, function definitions, option settings) for particular tasks.
804 load, function definitions, option settings) for particular tasks.
812 You can then have customized versions of IPython for specific
805 You can then have customized versions of IPython for specific
813 purposes. See sec. 7.3 <node7.html#sec:profiles> for more.
806 purposes. See sec. profiles_ for more.
814 * Embed IPython in your programs. A few lines of code are enough to
807 * Embed IPython in your programs. A few lines of code are enough to
815 load a complete IPython inside your own programs, giving you the
808 load a complete IPython inside your own programs, giving you the
816 ability to work with your data interactively after automatic
809 ability to work with your data interactively after automatic
817 processing has been completed. See sec. 9 <node9.html#sec:embed>
810 processing has been completed. See sec. embedding_
818 for more.
811 for more.
819 * Use the Python profiler. When dealing with performance issues, the
812 * Use the Python profiler. When dealing with performance issues, the
820 %run command with a -p option allows you to run complete programs
813 %run command with a -p option allows you to run complete programs
821 under the control of the Python profiler. The %prun command does a
814 under the control of the Python profiler. The %prun command does a
822 similar job for single Python expressions (like function calls).
815 similar job for single Python expressions (like function calls).
823 * Use the IPython.demo.Demo class to load any Python script as an
816 * Use the IPython.demo.Demo class to load any Python script as an
824 interactive demo. With a minimal amount of simple markup, you can
817 interactive demo. With a minimal amount of simple markup, you can
825 control the execution of the script, stopping as needed. See
818 control the execution of the script, stopping as needed. See
826 sec. 14 <node14.html#sec:interactive-demos> for more.
819 sec. `interactive demos`_ for more.
827 * Run your doctests from within IPython for development and
820 * Run your doctests from within IPython for development and
828 debugging. The special %doctest_mode command toggles a mode where
821 debugging. The special %doctest_mode command toggles a mode where
829 the prompt, output and exceptions display matches as closely as
822 the prompt, output and exceptions display matches as closely as
830 possible that of the default Python interpreter. In addition, this
823 possible that of the default Python interpreter. In addition, this
831 mode allows you to directly paste in code that contains leading
824 mode allows you to directly paste in code that contains leading
832 '>>>' prompts, even if they have extra leading whitespace (as is
825 '>>>' prompts, even if they have extra leading whitespace (as is
833 common in doctest files). This combined with the '%history -tn'
826 common in doctest files). This combined with the '%history -tn'
834 call to see your translated history (with these extra prompts
827 call to see your translated history (with these extra prompts
835 removed and no line numbers) allows for an easy doctest workflow,
828 removed and no line numbers) allows for an easy doctest workflow,
836 where you can go from doctest to interactive execution to pasting
829 where you can go from doctest to interactive execution to pasting
837 into valid Python code as needed.
830 into valid Python code as needed.
838
831
839
832
840 Source code handling tips
833 Source code handling tips
841 -------------------------
834 -------------------------
842
835
843 IPython is a line-oriented program, without full control of the
836 IPython is a line-oriented program, without full control of the
844 terminal. Therefore, it doesn't support true multiline editing. However,
837 terminal. Therefore, it doesn't support true multiline editing. However,
845 it has a number of useful tools to help you in dealing effectively with
838 it has a number of useful tools to help you in dealing effectively with
846 more complex editing.
839 more complex editing.
847
840
848 The %edit command gives a reasonable approximation of multiline editing,
841 The %edit command gives a reasonable approximation of multiline editing,
849 by invoking your favorite editor on the spot. IPython will execute the
842 by invoking your favorite editor on the spot. IPython will execute the
850 code you type in there as if it were typed interactively. Type %edit?
843 code you type in there as if it were typed interactively. Type %edit?
851 for the full details on the edit command.
844 for the full details on the edit command.
852
845
853 If you have typed various commands during a session, which you'd like to
846 If you have typed various commands during a session, which you'd like to
854 reuse, IPython provides you with a number of tools. Start by using %hist
847 reuse, IPython provides you with a number of tools. Start by using %hist
855 to see your input history, so you can see the line numbers of all input.
848 to see your input history, so you can see the line numbers of all input.
856 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
849 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
857 and 28. All the commands below can operate on these with the syntax::
850 and 28. All the commands below can operate on these with the syntax::
858
851
859 %command 10-20 24 28
852 %command 10-20 24 28
860
853
861 where the command given can be:
854 where the command given can be:
862
855
863 * %macro <macroname>: this stores the lines into a variable which,
856 * %macro <macroname>: this stores the lines into a variable which,
864 when called at the prompt, re-executes the input. Macros can be
857 when called at the prompt, re-executes the input. Macros can be
865 edited later using '%edit macroname', and they can be stored
858 edited later using '%edit macroname', and they can be stored
866 persistently across sessions with '%store macroname' (the storage
859 persistently across sessions with '%store macroname' (the storage
867 system is per-profile). The combination of quick macros,
860 system is per-profile). The combination of quick macros,
868 persistent storage and editing, allows you to easily refine
861 persistent storage and editing, allows you to easily refine
869 quick-and-dirty interactive input into permanent utilities, always
862 quick-and-dirty interactive input into permanent utilities, always
870 available both in IPython and as files for general reuse.
863 available both in IPython and as files for general reuse.
871 * %edit: this will open a text editor with those lines pre-loaded
864 * %edit: this will open a text editor with those lines pre-loaded
872 for further modification. It will then execute the resulting
865 for further modification. It will then execute the resulting
873 file's contents as if you had typed it at the prompt.
866 file's contents as if you had typed it at the prompt.
874 * %save <filename>: this saves the lines directly to a named file on
867 * %save <filename>: this saves the lines directly to a named file on
875 disk.
868 disk.
876
869
877 While %macro saves input lines into memory for interactive re-execution,
870 While %macro saves input lines into memory for interactive re-execution,
878 sometimes you'd like to save your input directly to a file. The %save
871 sometimes you'd like to save your input directly to a file. The %save
879 magic does this: its input sytnax is the same as %macro, but it saves
872 magic does this: its input sytnax is the same as %macro, but it saves
880 your input directly to a Python file. Note that the %logstart command
873 your input directly to a Python file. Note that the %logstart command
881 also saves input, but it logs all input to disk (though you can
874 also saves input, but it logs all input to disk (though you can
882 temporarily suspend it and reactivate it with %logoff/%logon); %save
875 temporarily suspend it and reactivate it with %logoff/%logon); %save
883 allows you to select which lines of input you need to save.
876 allows you to select which lines of input you need to save.
884
877
885
878
886 Lightweight 'version control'
879 Lightweight 'version control'
887 -----------------------------
880 -----------------------------
888
881
889 When you call %edit with no arguments, IPython opens an empty editor
882 When you call %edit with no arguments, IPython opens an empty editor
890 with a temporary file, and it returns the contents of your editing
883 with a temporary file, and it returns the contents of your editing
891 session as a string variable. Thanks to IPython's output caching
884 session as a string variable. Thanks to IPython's output caching
892 mechanism, this is automatically stored::
885 mechanism, this is automatically stored::
893
886
894 In [1]: %edit
887 In [1]: %edit
895
888
896 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
889 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
897
890
898 Editing... done. Executing edited code...
891 Editing... done. Executing edited code...
899
892
900 hello - this is a temporary file
893 hello - this is a temporary file
901
894
902 Out[1]: "print 'hello - this is a temporary file'\n"
895 Out[1]: "print 'hello - this is a temporary file'\n"
903
896
904 Now, if you call '%edit -p', IPython tries to open an editor with the
897 Now, if you call '%edit -p', IPython tries to open an editor with the
905 same data as the last time you used %edit. So if you haven't used %edit
898 same data as the last time you used %edit. So if you haven't used %edit
906 in the meantime, this same contents will reopen; however, it will be
899 in the meantime, this same contents will reopen; however, it will be
907 done in a new file. This means that if you make changes and you later
900 done in a new file. This means that if you make changes and you later
908 want to find an old version, you can always retrieve it by using its
901 want to find an old version, you can always retrieve it by using its
909 output number, via '%edit _NN', where NN is the number of the output
902 output number, via '%edit _NN', where NN is the number of the output
910 prompt.
903 prompt.
911
904
912 Continuing with the example above, this should illustrate this idea::
905 Continuing with the example above, this should illustrate this idea::
913
906
914 In [2]: edit -p
907 In [2]: edit -p
915
908
916 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
909 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
917
910
918 Editing... done. Executing edited code...
911 Editing... done. Executing edited code...
919
912
920 hello - now I made some changes
913 hello - now I made some changes
921
914
922 Out[2]: "print 'hello - now I made some changes'\n"
915 Out[2]: "print 'hello - now I made some changes'\n"
923
916
924 In [3]: edit _1
917 In [3]: edit _1
925
918
926 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
919 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
927
920
928 Editing... done. Executing edited code...
921 Editing... done. Executing edited code...
929
922
930 hello - this is a temporary file
923 hello - this is a temporary file
931
924
932 IPython version control at work :)
925 IPython version control at work :)
933
926
934 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
927 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
935
928
936
929
937 This section was written after a contribution by Alexander Belchenko on
930 This section was written after a contribution by Alexander Belchenko on
938 the IPython user list.
931 the IPython user list.
939
932
940
933
941 Effective logging
934 Effective logging
942 -----------------
935 -----------------
943
936
944 A very useful suggestion sent in by Robert Kern follows:
937 A very useful suggestion sent in by Robert Kern follows:
945
938
946 I recently happened on a nifty way to keep tidy per-project log files. I
939 I recently happened on a nifty way to keep tidy per-project log files. I
947 made a profile for my project (which is called "parkfield").
940 made a profile for my project (which is called "parkfield").
948
941
949 include ipythonrc
942 include ipythonrc
950
943
951 # cancel earlier logfile invocation:
944 # cancel earlier logfile invocation:
952
945
953 logfile ''
946 logfile ''
954
947
955 execute import time
948 execute import time
956
949
957 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
950 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
958
951
959 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
952 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
960
953
961 I also added a shell alias for convenience:
954 I also added a shell alias for convenience:
962
955
963 alias parkfield="ipython -pylab -profile parkfield"
956 alias parkfield="ipython -pylab -profile parkfield"
964
957
965 Now I have a nice little directory with everything I ever type in,
958 Now I have a nice little directory with everything I ever type in,
966 organized by project and date.
959 organized by project and date.
967
960
968 Contribute your own: If you have your own favorite tip on using IPython
961 Contribute your own: If you have your own favorite tip on using IPython
969 efficiently for a certain task (especially things which can't be done in
962 efficiently for a certain task (especially things which can't be done in
970 the normal Python interpreter), don't hesitate to send it!
963 the normal Python interpreter), don't hesitate to send it!
971
964
965 .. _Command line options:
966
972 Command-line use
967 Command-line use
973 ================
968 ================
974
969
975 You start IPython with the command::
970 You start IPython with the command::
976
971
977 $ ipython [options] files
972 $ ipython [options] files
978
973
979 If invoked with no options, it executes all the files listed in sequence
974 If invoked with no options, it executes all the files listed in sequence
980 and drops you into the interpreter while still acknowledging any options
975 and drops you into the interpreter while still acknowledging any options
981 you may have set in your ipythonrc file. This behavior is different from
976 you may have set in your ipythonrc file. This behavior is different from
982 standard Python, which when called as python -i will only execute one
977 standard Python, which when called as python -i will only execute one
983 file and ignore your configuration setup.
978 file and ignore your configuration setup.
984
979
985 Please note that some of the configuration options are not available at
980 Please note that some of the configuration options are not available at
986 the command line, simply because they are not practical here. Look into
981 the command line, simply because they are not practical here. Look into
987 your ipythonrc configuration file for details on those. This file
982 your ipythonrc configuration file for details on those. This file
988 typically installed in the $HOME/.ipython directory. For Windows users,
983 typically installed in the $HOME/.ipython directory. For Windows users,
989 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
984 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
990 instances. In the rest of this text, we will refer to this directory as
985 instances. In the rest of this text, we will refer to this directory as
991 IPYTHONDIR.
986 IPYTHONDIR.
992
987
988 .. _Threading options:
989
993
990
994 Special Threading Options
991 Special Threading Options
992 -------------------------
995
993
996 The following special options are ONLY valid at the beginning of the
994 The following special options are ONLY valid at the beginning of the
997 command line, and not later. This is because they control the initial-
995 command line, and not later. This is because they control the initial-
998 ization of ipython itself, before the normal option-handling mechanism
996 ization of ipython itself, before the normal option-handling mechanism
999 is active.
997 is active.
1000
998
1001 * [-gthread, -qthread, -q4thread, -wthread, -pylab:] Only one of
999 -gthread, -qthread, -q4thread, -wthread, -pylab:
1002 these can be given, and it can only be given as the first option
1000 Only one of these can be given, and it can only be given as
1003 passed to IPython (it will have no effect in any other position).
1001 the first option passed to IPython (it will have no effect in
1004 They provide threading support for the GTK, Qt (versions 3 and 4)
1002 any other position). They provide threading support for the
1005 and WXPython toolkits, and for the matplotlib library.
1003 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
1006 * [ ] With any of the first four options, IPython starts running a
1004 matplotlib library.
1007 separate thread for the graphical toolkit's operation, so that you
1005
1008 can open and control graphical elements from within an IPython
1006 With any of the first four options, IPython starts running a
1009 command line, without blocking. All four provide essentially the
1007 separate thread for the graphical toolkit's operation, so that
1010 same functionality, respectively for GTK, Qt3, Qt4 and WXWidgets
1008 you can open and control graphical elements from within an
1011 (via their Python interfaces).
1009 IPython command line, without blocking. All four provide
1012 * [ ] Note that with -wthread, you can additionally use the
1010 essentially the same functionality, respectively for GTK, Qt3,
1013 -wxversion option to request a specific version of wx to be used.
1011 Qt4 and WXWidgets (via their Python interfaces).
1014 This requires that you have the wxversion Python module installed,
1012
1015 which is part of recent wxPython distributions.
1013 Note that with -wthread, you can additionally use the
1016 * [ ] If -pylab is given, IPython loads special support for the mat
1014 -wxversion option to request a specific version of wx to be
1017 plotlib library (http://matplotlib.sourceforge.net), allowing
1015 used. This requires that you have the wxversion Python module
1018 interactive usage of any of its backends as defined in the user's
1016 installed, which is part of recent wxPython distributions.
1019 ~/.matplotlib/matplotlibrc file. It automatically activates GTK,
1017
1020 Qt or WX threading for IPyhton if the choice of matplotlib backend
1018 If -pylab is given, IPython loads special support for the mat
1021 requires it. It also modifies the %run command to correctly
1019 plotlib library (http://matplotlib.sourceforge.net), allowing
1022 execute (without blocking) any matplotlib-based script which calls
1020 interactive usage of any of its backends as defined in the
1023 show() at the end.
1021 user's ~/.matplotlib/matplotlibrc file. It automatically
1024 * [-tk] The -g/q/q4/wthread options, and -pylab (if matplotlib is
1022 activates GTK, Qt or WX threading for IPyhton if the choice of
1025 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
1023 matplotlib backend requires it. It also modifies the %run
1026 graphical interfaces. This means that when either GTK, Qt or WX
1024 command to correctly execute (without blocking) any
1027 threading is active, any attempt to open a Tk GUI will result in a
1025 matplotlib-based script which calls show() at the end.
1028 dead window, and possibly cause the Python interpreter to crash.
1026
1029 An extra option, -tk, is available to address this issue. It can
1027 -tk
1030 only be given as a second option after any of the above (-gthread,
1028 The -g/q/q4/wthread options, and -pylab (if matplotlib is
1031 -wthread or -pylab).
1029 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
1032 * [ ] If -tk is given, IPython will try to coordinate Tk threading
1030 graphical interfaces. This means that when either GTK, Qt or WX
1033 with GTK, Qt or WX. This is however potentially unreliable, and
1031 threading is active, any attempt to open a Tk GUI will result in a
1034 you will have to test on your platform and Python configuration to
1032 dead window, and possibly cause the Python interpreter to crash.
1035 determine whether it works for you. Debian users have reported
1033 An extra option, -tk, is available to address this issue. It can
1036 success, apparently due to the fact that Debian builds all of Tcl,
1034 only be given as a second option after any of the above (-gthread,
1037 Tk, Tkinter and Python with pthreads support. Under other Linux
1035 -wthread or -pylab).
1038 environments (such as Fedora Core 2/3), this option has caused
1036
1039 random crashes and lockups of the Python interpreter. Under other
1037 If -tk is given, IPython will try to coordinate Tk threading
1040 operating systems (Mac OSX and Windows), you'll need to try it to
1038 with GTK, Qt or WX. This is however potentially unreliable, and
1041 find out, since currently no user reports are available.
1039 you will have to test on your platform and Python configuration to
1042 * [ ] There is unfortunately no way for IPython to determine at run
1040 determine whether it works for you. Debian users have reported
1043 time whether -tk will work reliably or not, so you will need to do
1041 success, apparently due to the fact that Debian builds all of Tcl,
1044 some experiments before relying on it for regular work.
1042 Tk, Tkinter and Python with pthreads support. Under other Linux
1043 environments (such as Fedora Core 2/3), this option has caused
1044 random crashes and lockups of the Python interpreter. Under other
1045 operating systems (Mac OSX and Windows), you'll need to try it to
1046 find out, since currently no user reports are available.
1047
1048 There is unfortunately no way for IPython to determine at run time
1049 whether -tk will work reliably or not, so you will need to do some
1050 experiments before relying on it for regular work.
1045
1051
1046
1052
1047
1053
1048 Regular Options
1054 Regular Options
1049 ---------------
1055 ---------------
1050
1056
1051 After the above threading options have been given, regular options can
1057 After the above threading options have been given, regular options can
1052 follow in any order. All options can be abbreviated to their shortest
1058 follow in any order. All options can be abbreviated to their shortest
1053 non-ambiguous form and are case-sensitive. One or two dashes can be
1059 non-ambiguous form and are case-sensitive. One or two dashes can be
1054 used. Some options have an alternate short form, indicated after a ``|``.
1060 used. Some options have an alternate short form, indicated after a ``|``.
1055
1061
1056 Most options can also be set from your ipythonrc configuration file. See
1062 Most options can also be set from your ipythonrc configuration file. See
1057 the provided example for more details on what the options do. Options
1063 the provided example for more details on what the options do. Options
1058 given at the command line override the values set in the ipythonrc file.
1064 given at the command line override the values set in the ipythonrc file.
1059
1065
1060 All options with a [no] prepended can be specified in negated form
1066 All options with a [no] prepended can be specified in negated form
1061 (-nooption instead of -option) to turn the feature off.
1067 (-nooption instead of -option) to turn the feature off.
1062
1068
1063 * [-help:] print a help message and exit.
1069 -help print a help message and exit.
1064 * [-pylab:] this can only be given as the first option passed to
1070
1065 IPython (it will have no effect in any other position). It adds
1071 -pylab
1066 special support for the matplotlib library
1072 this can only be given as the first option passed to IPython
1067 (http://matplotlib.sourceforge.net
1073 (it will have no effect in any other position). It adds
1068 http://matplotlib.sourceforge.net), allowing interactive usage of
1074 special support for the matplotlib library
1069 any of its backends as defined in the user's .matplotlibrc file.
1075 (http://matplotlib.sourceforge.ne), allowing interactive usage
1070 It automatically activates GTK or WX threading for IPyhton if the
1076 of any of its backends as defined in the user's .matplotlibrc
1071 choice of matplotlib backend requires it. It also modifies the
1077 file. It automatically activates GTK or WX threading for
1072 %run command to correctly execute (without blocking) any
1078 IPyhton if the choice of matplotlib backend requires it. It
1073 matplotlib-based script which calls show() at the end. See Sec. 15
1079 also modifies the %run command to correctly execute (without
1074 <node15.html#sec:matplotlib-support> for more details.
1080 blocking) any matplotlib-based script which calls show() at
1075 * [-autocall] <val>: Make IPython automatically call any callable
1081 the end. See `Matplotlib support`_ for more details.
1076 object even if you didn't type explicit parentheses. For example,
1082
1077 'str 43' becomes 'str(43)' automatically. The value can be '0' to
1083 -autocall <val>
1078 disable the feature, '1' for smart autocall, where it is not
1084 Make IPython automatically call any callable object even if you
1079 applied if there are no more arguments on the line, and '2' for
1085 didn't type explicit parentheses. For example, 'str 43' becomes
1080 full autocall, where all callable objects are automatically called
1086 'str(43)' automatically. The value can be '0' to disable the feature,
1081 (even if no arguments are present). The default is '1'.
1087 '1' for smart autocall, where it is not applied if there are no more
1082 * [-[no]autoindent:] Turn automatic indentation on/off.
1088 arguments on the line, and '2' for full autocall, where all callable
1083 * [-[no]automagic:] make magic commands automatic (without needing
1089 objects are automatically called (even if no arguments are
1084 their first character to be %). Type %magic at the IPython prompt
1090 present). The default is '1'.
1085 for more information.
1091
1086 * [-[no]autoedit_syntax:] When a syntax error occurs after editing a
1092 -[no]autoindent
1087 file, automatically open the file to the trouble causing line for
1093 Turn automatic indentation on/off.
1088 convenient fixing.
1094
1089 * [-[no]banner:] Print the initial information banner (default on).
1095 -[no]automagic
1090 * [-c <command>:] execute the given command string, and set sys.argv
1096 make magic commands automatic (without needing their first character
1091 to ['c']. This is similar to the -c option in the normal Python
1097 to be %). Type %magic at the IPython prompt for more information.
1092 interpreter.
1098
1093 * [-cache_size|cs <n>:] size of the output cache (maximum number of
1099 -[no]autoedit_syntax
1094 entries to hold in memory). The default is 1000, you can change it
1100 When a syntax error occurs after editing a file, automatically
1095 permanently in your config file. Setting it to 0 completely
1101 open the file to the trouble causing line for convenient
1096 disables the caching system, and the minimum value accepted is 20
1102 fixing.
1097 (if you provide a value less than 20, it is reset to 0 and a
1103
1098 warning is issued) This limit is defined because otherwise you'll
1104 -[no]banner Print the initial information banner (default on).
1099 spend more time re-flushing a too small cache than working.
1105
1100 * [-classic|cl:] Gives IPython a similar feel to the classic Python
1106 -c <command>
1101 prompt.
1107 execute the given command string. This is similar to the -c
1102 * [-colors <scheme>:] Color scheme for prompts and exception
1108 option in the normal Python interpreter.
1103 reporting. Currently implemented: NoColor, Linux and LightBG.
1109
1104 * [-[no]color_info:] IPython can display information about objects
1110 -cache_size, cs <n>
1105 via a set of functions, and optionally can use colors for this,
1111 size of the output cache (maximum number of entries to hold in
1106 syntax highlighting source code and various other elements.
1112 memory). The default is 1000, you can change it permanently in your
1107 However, because this information is passed through a pager (like
1113 config file. Setting it to 0 completely disables the caching system,
1108 'less') and many pagers get confused with color codes, this option
1114 and the minimum value accepted is 20 (if you provide a value less than
1109 is off by default. You can test it and turn it on permanently in
1115 20, it is reset to 0 and a warning is issued) This limit is defined
1110 your ipythonrc file if it works for you. As a reference, the
1116 because otherwise you'll spend more time re-flushing a too small cache
1111 'less' pager supplied with Mandrake 8.2 works ok, but that in
1117 than working.
1112 RedHat 7.2 doesn't.
1118
1113 * [ ] Test it and turn it on permanently if it works with your
1119 -classic, cl
1114 system. The magic function %color_info allows you to toggle this
1120 Gives IPython a similar feel to the classic Python
1115 interactively for testing.
1121 prompt.
1116 * [-[no]debug:] Show information about the loading process. Very
1122
1117 useful to pin down problems with your configuration files or to
1123 -colors <scheme>
1118 get details about session restores.
1124 Color scheme for prompts and exception reporting. Currently
1119 * [-[no]deep_reload:] IPython can use the deep_reload module which
1125 implemented: NoColor, Linux and LightBG.
1120 reloads changes in modules recursively (it replaces the reload()
1126
1121 function, so you don't need to change anything to use it).
1127 -[no]color_info
1122 deep_reload() forces a full reload of modules whose code may have
1128 IPython can display information about objects via a set of functions,
1123 changed, which the default reload() function does not.
1129 and optionally can use colors for this, syntax highlighting source
1124 * [ ] When deep_reload is off, IPython will use the normal reload(),
1130 code and various other elements. However, because this information is
1125 but deep_reload will still be available as dreload(). This feature
1131 passed through a pager (like 'less') and many pagers get confused with
1126 is off by default [which means that you have both normal reload()
1132 color codes, this option is off by default. You can test it and turn
1127 and dreload()].
1133 it on permanently in your ipythonrc file if it works for you. As a
1128 * [-editor <name>:] Which editor to use with the %edit command. By
1134 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
1129 default, IPython will honor your EDITOR environment variable (if
1135 that in RedHat 7.2 doesn't.
1130 not set, vi is the Unix default and notepad the Windows one).
1136
1131 Since this editor is invoked on the fly by IPython and is meant
1137 Test it and turn it on permanently if it works with your
1132 for editing small code snippets, you may want to use a small,
1138 system. The magic function %color_info allows you to toggle this
1133 lightweight editor here (in case your default EDITOR is something
1139 interactively for testing.
1134 like Emacs).
1140
1135 * [-ipythondir <name>:] name of your IPython configuration directory
1141 -[no]debug
1136 IPYTHONDIR. This can also be specified through the environment
1142 Show information about the loading process. Very useful to pin down
1137 variable IPYTHONDIR.
1143 problems with your configuration files or to get details about
1138 * [-log|l:] generate a log file of all input. The file is named
1144 session restores.
1139 ipython_log.py in your current directory (which prevents logs from
1145
1140 multiple IPython sessions from trampling each other). You can use
1146 -[no]deep_reload:
1141 this to later restore a session by loading your logfile as a file
1147 IPython can use the deep_reload module which reloads changes in
1142 to be executed with option -logplay (see below).
1148 modules recursively (it replaces the reload() function, so you don't
1143 * [-logfile|lf <name>:] specify the name of your logfile.
1149 need to change anything to use it). deep_reload() forces a full
1144 * [-logplay|lp <name>:] you can replay a previous log. For restoring
1150 reload of modules whose code may have changed, which the default
1145 a session as close as possible to the state you left it in, use
1151 reload() function does not.
1146 this option (don't just run the logfile). With -logplay, IPython
1152
1147 will try to reconstruct the previous working environment in full,
1153 When deep_reload is off, IPython will use the normal reload(),
1148 not just execute the commands in the logfile.
1154 but deep_reload will still be available as dreload(). This
1149 * [ ] When a session is restored, logging is automatically turned on
1155 feature is off by default [which means that you have both
1150 again with the name of the logfile it was invoked with (it is read
1156 normal reload() and dreload()].
1151 from the log header). So once you've turned logging on for a
1157
1152 session, you can quit IPython and reload it as many times as you
1158 -editor <name>
1153 want and it will continue to log its history and restore from the
1159 Which editor to use with the %edit command. By default,
1154 beginning every time.
1160 IPython will honor your EDITOR environment variable (if not
1155 * [ ] Caveats: there are limitations in this option. The history
1161 set, vi is the Unix default and notepad the Windows one).
1162 Since this editor is invoked on the fly by IPython and is
1163 meant for editing small code snippets, you may want to use a
1164 small, lightweight editor here (in case your default EDITOR is
1165 something like Emacs).
1166
1167 -ipythondir <name>
1168 name of your IPython configuration directory IPYTHONDIR. This
1169 can also be specified through the environment variable
1170 IPYTHONDIR.
1171
1172 -log, l
1173 generate a log file of all input. The file is named
1174 ipython_log.py in your current directory (which prevents logs
1175 from multiple IPython sessions from trampling each other). You
1176 can use this to later restore a session by loading your
1177 logfile as a file to be executed with option -logplay (see
1178 below).
1179
1180 -logfile, lf <name> specify the name of your logfile.
1181
1182 -logplay, lp <name>
1183
1184 you can replay a previous log. For restoring a session as close as
1185 possible to the state you left it in, use this option (don't just run
1186 the logfile). With -logplay, IPython will try to reconstruct the
1187 previous working environment in full, not just execute the commands in
1188 the logfile.
1189
1190 When a session is restored, logging is automatically turned on
1191 again with the name of the logfile it was invoked with (it is
1192 read from the log header). So once you've turned logging on for
1193 a session, you can quit IPython and reload it as many times as
1194 you want and it will continue to log its history and restore
1195 from the beginning every time.
1196
1197 Caveats: there are limitations in this option. The history
1156 variables _i*,_* and _dh don't get restored properly. In the
1198 variables _i*,_* and _dh don't get restored properly. In the
1157 future we will try to implement full session saving by writing and
1199 future we will try to implement full session saving by writing
1158 retrieving a 'snapshot' of the memory state of IPython. But our
1200 and retrieving a 'snapshot' of the memory state of IPython. But
1159 first attempts failed because of inherent limitations of Python's
1201 our first attempts failed because of inherent limitations of
1160 Pickle module, so this may have to wait.
1202 Python's Pickle module, so this may have to wait.
1161 * [-[no]messages:] Print messages which IPython collects about its
1203
1162 startup process (default on).
1204 -[no]messages
1163 * [-[no]pdb:] Automatically call the pdb debugger after every
1205 Print messages which IPython collects about its startup
1164 uncaught exception. If you are used to debugging using pdb, this
1206 process (default on).
1165 puts you automatically inside of it after any call (either in
1207
1166 IPython or in code called by it) which triggers an exception which
1208 -[no]pdb
1167 goes uncaught.
1209 Automatically call the pdb debugger after every uncaught
1168 * [-[no]pprint:] ipython can optionally use the pprint (pretty
1210 exception. If you are used to debugging using pdb, this puts
1169 printer) module for displaying results. pprint tends to give a
1211 you automatically inside of it after any call (either in
1170 nicer display of nested data structures. If you like it, you can
1212 IPython or in code called by it) which triggers an exception
1171 turn it on permanently in your config file (default off).
1213 which goes uncaught.
1172 * [-profile|p] <name>: assume that your config file is
1214
1173 ipythonrc-<name> (looks in current dir first, then in IPYTHONDIR).
1215 -[no]pprint
1174 This is a quick way to keep and load multiple config files for
1216 ipython can optionally use the pprint (pretty printer) module
1175 different tasks, especially if you use the include option of
1217 for displaying results. pprint tends to give a nicer display
1176 config files. You can keep a basic IPYTHONDIR/ipythonrc file and
1218 of nested data structures. If you like it, you can turn it on
1177 then have other 'profiles' which include this one and load extra
1219 permanently in your config file (default off).
1178 things for particular tasks. For example:
1220
1179 * [ ] 1. $HOME/.ipython/ipythonrc : load basic things you always want.
1221 -profile, p <name>
1180 * [ ] 2. $HOME/.ipython/ipythonrc-math : load (1) and basic
1222
1181 math-related modules.
1223 assume that your config file is ipythonrc-<name> or
1182 * [ ] 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
1224 ipy_profile_<name>.py (looks in current dir first, then in
1183 plotting modules.
1225 IPYTHONDIR). This is a quick way to keep and load multiple
1184 * [ ] Since it is possible to create an endless loop by having
1226 config files for different tasks, especially if you use the
1185 circular file inclusions, IPython will stop if it reaches 15
1227 include option of config files. You can keep a basic
1186 recursive inclusions.
1228 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
1187 * [-prompt_in1|pi1 <string>:] Specify the string used for input
1229 include this one and load extra things for particular
1188 prompts. Note that if you are using numbered prompts, the number
1230 tasks. For example:
1189 is represented with a '\#' in the string. Don't forget to quote
1231
1190 strings with spaces embedded in them. Default: 'In [\#]:'.
1232 1. $HOME/.ipython/ipythonrc : load basic things you always want.
1191 Sec. 7.2 <node7.html#sec:prompts> discusses in detail all the
1233 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
1192 available escapes to customize your prompts.
1234 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
1193 * [-prompt_in2|pi2 <string>:] Similar to the previous option, but
1235
1194 used for the continuation prompts. The special sequence '\D' is
1236 Since it is possible to create an endless loop by having
1195 similar to '\#', but with all digits replaced dots (so you can
1237 circular file inclusions, IPython will stop if it reaches 15
1196 have your continuation prompt aligned with your input prompt).
1238 recursive inclusions.
1197 Default: ' .\D.:' (note three spaces at the start for alignment
1239
1198 with 'In [\#]').
1240 -prompt_in1, pi1 <string>
1199 * [-prompt_out|po <string>:] String used for output prompts, also
1241 Specify the string used for input prompts. Note that if you
1200 uses numbers like prompt_in1. Default: 'Out[\#]:'
1242 are using numbered prompts, the number is represented with a
1201 * [-quick:] start in bare bones mode (no config file loaded).
1243 '\#' in the string. Don't forget to quote strings with spaces
1202 * [-rcfile <name>:] name of your IPython resource configuration
1244 embedded in them. Default: 'In [\#]:'. Sec. Prompts_
1203 file. Normally IPython loads ipythonrc (from current directory) or
1245 discusses in detail all the available escapes to customize
1204 IPYTHONDIR/ipythonrc.
1246 your prompts.
1205 * [ ] If the loading of your config file fails, IPython starts with
1247
1206 a bare bones configuration (no modules loaded at all).
1248 -prompt_in2, pi2 <string>
1207 * [-[no]readline:] use the readline library, which is needed to
1249 Similar to the previous option, but used for the continuation
1208 support name completion and command history, among other things.
1250 prompts. The special sequence '\D' is similar to '\#', but
1209 It is enabled by default, but may cause problems for users of
1251 with all digits replaced dots (so you can have your
1210 X/Emacs in Python comint or shell buffers.
1252 continuation prompt aligned with your input prompt). Default:
1211 * [ ] Note that X/Emacs 'eterm' buffers (opened with M-x term)
1253 ' .\D.:' (note three spaces at the start for alignment with
1212 support IPython's readline and syntax coloring fine, only 'emacs'
1254 'In [\#]').
1213 (M-x shell and C-c !) buffers do not.
1255
1214 * [-screen_length|sl <n>:] number of lines of your screen. This is
1256 -prompt_out,po <string>
1215 used to control printing of very long strings. Strings longer than
1257 String used for output prompts, also uses numbers like
1216 this number of lines will be sent through a pager instead of
1258 prompt_in1. Default: 'Out[\#]:'
1217 directly printed.
1259
1218 * [ ] The default value for this is 0, which means IPython will
1260 -quick start in bare bones mode (no config file loaded).
1219 auto-detect your screen size every time it needs to print certain
1261
1220 potentially long strings (this doesn't change the behavior of the
1262 -rcfile <name>
1221 'print' keyword, it's only triggered internally). If for some
1263 name of your IPython resource configuration file. Normally
1222 reason this isn't working well (it needs curses support), specify
1264 IPython loads ipythonrc (from current directory) or
1223 it yourself. Otherwise don't change the default.
1265 IPYTHONDIR/ipythonrc.
1224 * [-separate_in|si <string>:] separator before input prompts.
1266
1225 Default: '\n'
1267 If the loading of your config file fails, IPython starts with
1226 * [-separate_out|so <string>:] separator before output prompts.
1268 a bare bones configuration (no modules loaded at all).
1227 Default: nothing.
1269
1228 * [-separate_out2|so2 <string>:] separator after output prompts.
1270 -[no]readline
1229 Default: nothing.
1271 use the readline library, which is needed to support name
1230 * [ ] For these three options, use the value 0 to specify no separator.
1272 completion and command history, among other things. It is
1231 * [-nosep:] shorthand for '-SeparateIn 0 -SeparateOut 0
1273 enabled by default, but may cause problems for users of
1232 -SeparateOut2 0'. Simply removes all input/output separators.
1274 X/Emacs in Python comint or shell buffers.
1233 * [-upgrade:] allows you to upgrade your IPYTHONDIR configuration
1275
1234 when you install a new version of IPython. Since new versions may
1276 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
1235 include new command line options or example files, this copies
1277 IPython's readline and syntax coloring fine, only 'emacs' (M-x
1236 updated ipythonrc-type files. However, it backs up (with a .old
1278 shell and C-c !) buffers do not.
1237 extension) all files which it overwrites so that you can merge
1279
1238 back any customizations you might have in your personal files.
1280 -screen_length, sl <n>
1239 * [-Version:] print version information and exit.
1281 number of lines of your screen. This is used to control
1240 * [-wxversion <string>:] Select a specific version of wxPython (used
1282 printing of very long strings. Strings longer than this number
1241 in conjunction with -wthread). Requires the wxversion module, part
1283 of lines will be sent through a pager instead of directly
1242 of recent wxPython distributions
1284 printed.
1243 * [-xmode <modename>:] Mode for exception reporting.
1285
1244 * [ ] Valid modes: Plain, Context and Verbose.
1286 The default value for this is 0, which means IPython will
1245 * [ ] Plain: similar to python's normal traceback printing.
1287 auto-detect your screen size every time it needs to print certain
1246 * [ ] Context: prints 5 lines of context source code around each
1288 potentially long strings (this doesn't change the behavior of the
1247 line in the traceback.
1289 'print' keyword, it's only triggered internally). If for some
1248 * [ ] Verbose: similar to Context, but additionally prints the
1290 reason this isn't working well (it needs curses support), specify
1249 variables currently visible where the exception happened
1291 it yourself. Otherwise don't change the default.
1250 (shortening their strings if too long). This can potentially be
1292
1251 very slow, if you happen to have a huge data structure whose
1293 -separate_in, si <string>
1252 string representation is complex to compute. Your computer may
1294
1253 appear to freeze for a while with cpu usage at 100%. If this
1295 separator before input prompts.
1254 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
1296 Default: '\n'
1255 more than once).
1297
1298 -separate_out, so <string>
1299 separator before output prompts.
1300 Default: nothing.
1301
1302 -separate_out2, so2
1303 separator after output prompts.
1304 Default: nothing.
1305 For these three options, use the value 0 to specify no separator.
1306
1307 -nosep
1308 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
1309 0'. Simply removes all input/output separators.
1310
1311 -upgrade
1312 allows you to upgrade your IPYTHONDIR configuration when you
1313 install a new version of IPython. Since new versions may
1314 include new command line options or example files, this copies
1315 updated ipythonrc-type files. However, it backs up (with a
1316 .old extension) all files which it overwrites so that you can
1317 merge back any customizations you might have in your personal
1318 files. Note that you should probably use %upgrade instead,
1319 it's a safer alternative.
1320
1321
1322 -Version print version information and exit.
1323
1324 -wxversion <string>
1325 Select a specific version of wxPython (used in conjunction
1326 with -wthread). Requires the wxversion module, part of recent
1327 wxPython distributions
1328
1329 -xmode <modename>
1330
1331 Mode for exception reporting.
1332
1333 Valid modes: Plain, Context and Verbose.
1334
1335 * Plain: similar to python's normal traceback printing.
1336 * Context: prints 5 lines of context source code around each
1337 line in the traceback.
1338 * Verbose: similar to Context, but additionally prints the
1339 variables currently visible where the exception happened
1340 (shortening their strings if too long). This can potentially be
1341 very slow, if you happen to have a huge data structure whose
1342 string representation is complex to compute. Your computer may
1343 appear to freeze for a while with cpu usage at 100%. If this
1344 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
1345 more than once).
1256
1346
1257 Interactive use
1347 Interactive use
1258 ===============
1348 ===============
1259
1349
1260 Warning: IPython relies on the existence of a global variable called
1350 Warning: IPython relies on the existence of a global variable called
1261 __IP which controls the shell itself. If you redefine __IP to anything,
1351 _ip which controls the shell itself. If you redefine _ip to anything,
1262 bizarre behavior will quickly occur.
1352 bizarre behavior will quickly occur.
1263
1353
1264 Other than the above warning, IPython is meant to work as a drop-in
1354 Other than the above warning, IPython is meant to work as a drop-in
1265 replacement for the standard interactive interpreter. As such, any code
1355 replacement for the standard interactive interpreter. As such, any code
1266 which is valid python should execute normally under IPython (cases where
1356 which is valid python should execute normally under IPython (cases where
1267 this is not true should be reported as bugs). It does, however, offer
1357 this is not true should be reported as bugs). It does, however, offer
1268 many features which are not available at a standard python prompt. What
1358 many features which are not available at a standard python prompt. What
1269 follows is a list of these.
1359 follows is a list of these.
1270
1360
1271
1361
1272 Caution for Windows users
1362 Caution for Windows users
1273 -------------------------
1363 -------------------------
1274
1364
1275 Windows, unfortunately, uses the '\' character as a path separator. This
1365 Windows, unfortunately, uses the '\' character as a path
1276 is a terrible choice, because '\' also represents the escape character
1366 separator. This is a terrible choice, because '\' also represents the
1277 in most modern programming languages, including Python. For this reason,
1367 escape character in most modern programming languages, including
1278 issuing many of the commands discussed below (especially magics which
1368 Python. For this reason, using '/' character is recommended if you
1279 affect the filesystem) with '\' in them will cause strange errors.
1369 have problems with ``\``. However, in Windows commands '/' flags
1280
1370 options, so you can not use it for the root directory. This means that
1281 A partial solution is to use instead the '/' character as a path
1371 paths beginning at the root must be typed in a contrived manner like:
1282 separator, which Windows recognizes in most situations. However, in
1372 ``%copy \opt/foo/bar.txt \tmp``
1283 Windows commands '/' flags options, so you can not use it for the root
1284 directory. This means that paths beginning at the root must be typed in
1285 a contrived manner like:
1286 %copy \opt/foo/bar.txt \tmp
1287
1288 There is no sensible thing IPython can do to truly work around this flaw
1289 in Windows^3 <footnode.html#foot878>.
1290
1291
1373
1374 .. _magic:
1292
1375
1293 Magic command system
1376 Magic command system
1294 --------------------
1377 --------------------
1295
1378
1296 IPython will treat any line whose first character is a % as a special
1379 IPython will treat any line whose first character is a % as a special
1297 call to a 'magic' function. These allow you to control the behavior of
1380 call to a 'magic' function. These allow you to control the behavior of
1298 IPython itself, plus a lot of system-type features. They are all
1381 IPython itself, plus a lot of system-type features. They are all
1299 prefixed with a % character, but parameters are given without
1382 prefixed with a % character, but parameters are given without
1300 parentheses or quotes.
1383 parentheses or quotes.
1301
1384
1302 Example: typing '%cd mydir' (without the quotes) changes you working
1385 Example: typing '%cd mydir' (without the quotes) changes you working
1303 directory to 'mydir', if it exists.
1386 directory to 'mydir', if it exists.
1304
1387
1305 If you have 'automagic' enabled (in your ipythonrc file, via the command
1388 If you have 'automagic' enabled (in your ipythonrc file, via the command
1306 line option -automagic or with the %automagic function), you don't need
1389 line option -automagic or with the %automagic function), you don't need
1307 to type in the % explicitly. IPython will scan its internal list of
1390 to type in the % explicitly. IPython will scan its internal list of
1308 magic functions and call one if it exists. With automagic on you can
1391 magic functions and call one if it exists. With automagic on you can
1309 then just type 'cd mydir' to go to directory 'mydir'. The automagic
1392 then just type 'cd mydir' to go to directory 'mydir'. The automagic
1310 system has the lowest possible precedence in name searches, so defining
1393 system has the lowest possible precedence in name searches, so defining
1311 an identifier with the same name as an existing magic function will
1394 an identifier with the same name as an existing magic function will
1312 shadow it for automagic use. You can still access the shadowed magic
1395 shadow it for automagic use. You can still access the shadowed magic
1313 function by explicitly using the % character at the beginning of the line.
1396 function by explicitly using the % character at the beginning of the line.
1314
1397
1315 An example (with automagic on) should clarify all this::
1398 An example (with automagic on) should clarify all this::
1316
1399
1317 In [1]: cd ipython # %cd is called by automagic
1400 In [1]: cd ipython # %cd is called by automagic
1318
1401
1319 /home/fperez/ipython
1402 /home/fperez/ipython
1320
1403
1321 In [2]: cd=1 # now cd is just a variable
1404 In [2]: cd=1 # now cd is just a variable
1322
1405
1323 In [3]: cd .. # and doesn't work as a function anymore
1406 In [3]: cd .. # and doesn't work as a function anymore
1324
1407
1325 ------------------------------
1408 ------------------------------
1326
1409
1327 File "<console>", line 1
1410 File "<console>", line 1
1328
1411
1329 cd ..
1412 cd ..
1330
1413
1331 ^
1414 ^
1332
1415
1333 SyntaxError: invalid syntax
1416 SyntaxError: invalid syntax
1334
1417
1335 In [4]: %cd .. # but %cd always works
1418 In [4]: %cd .. # but %cd always works
1336
1419
1337 /home/fperez
1420 /home/fperez
1338
1421
1339 In [5]: del cd # if you remove the cd variable
1422 In [5]: del cd # if you remove the cd variable
1340
1423
1341 In [6]: cd ipython # automagic can work again
1424 In [6]: cd ipython # automagic can work again
1342
1425
1343 /home/fperez/ipython
1426 /home/fperez/ipython
1344
1427
1345 You can define your own magic functions to extend the system. The
1428 You can define your own magic functions to extend the system. The
1346 following example defines a new magic command, %impall::
1429 following example defines a new magic command, %impall::
1347
1430
1348 import IPython.ipapi
1431 import IPython.ipapi
1349
1432
1350 ip = IPython.ipapi.get()
1433 ip = IPython.ipapi.get()
1351
1434
1352 def doimp(self, arg):
1435 def doimp(self, arg):
1353
1436
1354 ip = self.api
1437 ip = self.api
1355
1438
1356 ip.ex("import %s; reload(%s); from %s import *" % (
1439 ip.ex("import %s; reload(%s); from %s import *" % (
1357
1440
1358 arg,arg,arg)
1441 arg,arg,arg)
1359
1442
1360 )
1443 )
1361
1444
1362 ip.expose_magic('impall', doimp)
1445 ip.expose_magic('impall', doimp)
1363
1446
1364 You can also define your own aliased names for magic functions. In your
1447 You can also define your own aliased names for magic functions. In your
1365 ipythonrc file, placing a line like:
1448 ipythonrc file, placing a line like:
1366
1449
1367 execute __IP.magic_cl = __IP.magic_clear
1450 execute __IP.magic_cl = __IP.magic_clear
1368
1451
1369 will define %cl as a new name for %clear.
1452 will define %cl as a new name for %clear.
1370
1453
1371 Type %magic for more information, including a list of all available
1454 Type %magic for more information, including a list of all available
1372 magic functions at any time and their docstrings. You can also type
1455 magic functions at any time and their docstrings. You can also type
1373 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
1456 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
1374 information on the '?' system) to get information about any particular
1457 information on the '?' system) to get information about any particular
1375 magic function you are interested in.
1458 magic function you are interested in.
1376
1459
1377
1460
1378 Magic commands
1461 Magic commands
1379 --------------
1462 --------------
1380
1463
1381 The rest of this section is automatically generated for each release
1464 The rest of this section is automatically generated for each release
1382 from the docstrings in the IPython code. Therefore the formatting is
1465 from the docstrings in the IPython code. Therefore the formatting is
1383 somewhat minimal, but this method has the advantage of having
1466 somewhat minimal, but this method has the advantage of having
1384 information always in sync with the code.
1467 information always in sync with the code.
1385
1468
1386 A list of all the magic commands available in IPython's default
1469 A list of all the magic commands available in IPython's default
1387 installation follows. This is similar to what you'll see by simply
1470 installation follows. This is similar to what you'll see by simply
1388 typing %magic at the prompt, but that will also give you information
1471 typing %magic at the prompt, but that will also give you information
1389 about magic commands you may have added as part of your personal
1472 about magic commands you may have added as part of your personal
1390 customizations.
1473 customizations.
1391
1474
1392 ::
1475 .. magic_start
1393
1476
1394 %Exit: Exit IPython without confirmation.
1477 **%Exit**::
1395
1478
1396
1479 Exit IPython without confirmation.
1397 %Pprint: Toggle pretty printing on/off.
1480
1398
1481 **%Pprint**::
1399
1482
1400 %alias: Define an alias for a system command.
1483 Toggle pretty printing on/off.
1401
1484
1402 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1485 **%alias**::
1403
1486
1404 Then, typing 'alias_name params' will execute the system command 'cmd
1487 Define an alias for a system command.
1405 params' (from your underlying operating system).
1488
1406
1489 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1407 Aliases have lower precedence than magic functions and Python normal
1490
1408 variables, so if 'foo' is both a Python variable and an alias, the alias
1491 Then, typing 'alias_name params' will execute the system command 'cmd
1409 can not be executed until 'del foo' removes the Python variable.
1492 params' (from your underlying operating system).
1410
1493
1411 You can use the %l specifier in an alias definition to represent the
1494 Aliases have lower precedence than magic functions and Python normal
1412 whole line when the alias is called. For example:
1495 variables, so if 'foo' is both a Python variable and an alias, the
1413
1496 alias can not be executed until 'del foo' removes the Python variable.
1414 In [2]: alias all echo "Input in brackets: <%l>"
1497
1415 In [3]: all hello world
1498 You can use the %l specifier in an alias definition to represent the
1416 Input in brackets: <hello world>
1499 whole line when the alias is called. For example:
1417
1500
1418 You can also define aliases with parameters using %s specifiers (one per
1501 In [2]: alias all echo "Input in brackets: <%l>"\
1419 parameter):
1502 In [3]: all hello world\
1420
1503 Input in brackets: <hello world>
1421 In [1]: alias parts echo first %s second %s
1504
1422 In [2]: %parts A B
1505 You can also define aliases with parameters using %s specifiers (one
1423 first A second B
1506 per parameter):
1424 In [3]: %parts A
1507
1425 Incorrect number of arguments: 2 expected.
1508 In [1]: alias parts echo first %s second %s\
1426 parts is an alias to: 'echo first %s second %s'
1509 In [2]: %parts A B\
1427
1510 first A second B\
1428 Note that %l and %s are mutually exclusive. You can only use one or the
1511 In [3]: %parts A\
1429 other in your aliases.
1512 Incorrect number of arguments: 2 expected.\
1430
1513 parts is an alias to: 'echo first %s second %s'
1431 Aliases expand Python variables just like system calls using ! or !! do:
1514
1432 all expressions prefixed with '$' get expanded. For details of the
1515 Note that %l and %s are mutually exclusive. You can only use one or
1433 semantic rules, see PEP-215: http://www.python.org/peps/pep-0215.html.
1516 the other in your aliases.
1434 This is the library used by IPython for variable expansion. If you want
1517
1435 to access a true shell variable, an extra $ is necessary to prevent its
1518 Aliases expand Python variables just like system calls using ! or !!
1436 expansion by IPython:
1519 do: all expressions prefixed with '$' get expanded. For details of
1437
1520 the semantic rules, see PEP-215:
1438 In [6]: alias show echo
1521 http://www.python.org/peps/pep-0215.html. This is the library used by
1439 In [7]: PATH='A Python string'
1522 IPython for variable expansion. If you want to access a true shell
1440 In [8]: show $PATH
1523 variable, an extra $ is necessary to prevent its expansion by IPython:
1441 A Python string
1524
1442 In [9]: show $$PATH
1525 In [6]: alias show echo\
1443 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1526 In [7]: PATH='A Python string'\
1444
1527 In [8]: show $PATH\
1445 You can use the alias facility to acess all of $PATH. See the %rehash
1528 A Python string\
1446 and %rehashx functions, which automatically create aliases for the
1529 In [9]: show $$PATH\
1447 contents of your $PATH.
1530 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1448
1531
1449 If called with no parameters, %alias prints the current alias table.
1532 You can use the alias facility to acess all of $PATH. See the %rehash
1450
1533 and %rehashx functions, which automatically create aliases for the
1451
1534 contents of your $PATH.
1452 %autocall: Make functions callable without having to type parentheses.
1535
1453
1536 If called with no parameters, %alias prints the current alias table.
1454 Usage:
1537
1455
1538 **%autocall**::
1456 %autocall [mode]
1539
1457
1540 Make functions callable without having to type parentheses.
1458 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1541
1459 value is toggled on and off (remembering the previous state).
1542 Usage:
1460
1543
1461 In more detail, these values mean:
1544 %autocall [mode]
1462
1545
1463 0 -> fully disabled
1546 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
1464
1547 value is toggled on and off (remembering the previous state).
1465 1 -> active, but do not apply if there are no arguments on the line.
1548
1466
1549 In more detail, these values mean:
1467 In this mode, you get:
1550
1468
1551 0 -> fully disabled
1469 In [1]: callable Out[1]: <built-in function callable>
1552
1470
1553 1 -> active, but do not apply if there are no arguments on the line.
1471 In [2]: callable 'hello' ---> callable('hello') Out[2]: False
1554
1472
1555 In this mode, you get:
1473 2 -> Active always. Even if no arguments are present, the callable
1556
1474 object is called:
1557 In [1]: callable
1475
1558 Out[1]: <built-in function callable>
1476 In [4]: callable ---> callable()
1559
1477
1560 In [2]: callable 'hello'
1478 Note that even with autocall off, you can still use '/' at the start of
1561 ------> callable('hello')
1479 a line to treat the first argument on the command line as a function and
1562 Out[2]: False
1480 add parentheses to it:
1563
1481
1564 2 -> Active always. Even if no arguments are present, the callable
1482 In [8]: /str 43 ---> str(43) Out[8]: '43'
1565 object is called:
1483
1566
1484
1567 In [4]: callable
1485 %autoindent: Toggle autoindent on/off (if available).
1568 ------> callable()
1486
1569
1487
1570 Note that even with autocall off, you can still use '/' at the start of
1488 %automagic: Make magic functions callable without having to type the
1571 a line to treat the first argument on the command line as a function
1489 initial %.
1572 and add parentheses to it:
1490
1573
1491 Without argumentsl toggles on/off (when off, you must call it as
1574 In [8]: /str 43
1492 %automagic, of course). With arguments it sets the value, and you can
1575 ------> str(43)
1493 use any of (case insensitive):
1576 Out[8]: '43'
1494
1577
1495 - on,1,True: to activate
1578 **%autoindent**::
1496
1579
1497 - off,0,False: to deactivate.
1580 Toggle autoindent on/off (if available).
1498
1581
1499 Note that magic functions have lowest priority, so if there's a variable
1582 **%automagic**::
1500 whose name collides with that of a magic fn, automagic won't work for
1583
1501 that function (you get the variable instead). However, if you delete the
1584 Make magic functions callable without having to type the initial %.
1502 variable (del var), the previously shadowed magic function becomes
1585
1503 visible to automagic again.
1586 Without argumentsl toggles on/off (when off, you must call it as
1504
1587 %automagic, of course). With arguments it sets the value, and you can
1505
1588 use any of (case insensitive):
1506 %bg: Run a job in the background, in a separate thread.
1589
1507
1590 - on,1,True: to activate
1508 For example,
1591
1509
1592 - off,0,False: to deactivate.
1510 %bg myfunc(x,y,z=1)
1593
1511
1594 Note that magic functions have lowest priority, so if there's a
1512 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1595 variable whose name collides with that of a magic fn, automagic won't
1513 execution starts, a message will be printed indicating the job number.
1596 work for that function (you get the variable instead). However, if you
1514 If your job number is 5, you can use
1597 delete the variable (del var), the previously shadowed magic function
1515
1598 becomes visible to automagic again.
1516 myvar = jobs.result(5) or myvar = jobs[5].result
1599
1517
1600 **%bg**::
1518 to assign this result to variable 'myvar'.
1601
1519
1602 Run a job in the background, in a separate thread.
1520 IPython has a job manager, accessible via the 'jobs' object. You can
1603
1521 type jobs? to get more information about it, and use jobs.<TAB> to see
1604 For example,
1522 its attributes. All attributes not starting with an underscore are meant
1605
1523 for public use.
1606 %bg myfunc(x,y,z=1)
1524
1607
1525 In particular, look at the jobs.new() method, which is used to create
1608 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
1526 new jobs. This magic %bg function is just a convenience wrapper around
1609 execution starts, a message will be printed indicating the job
1527 jobs.new(), for expression-based jobs. If you want to create a new job
1610 number. If your job number is 5, you can use
1528 with an explicit function object and arguments, you must call jobs.new()
1611
1529 directly.
1612 myvar = jobs.result(5) or myvar = jobs[5].result
1530
1613
1531 The jobs.new docstring also describes in detail several important
1614 to assign this result to variable 'myvar'.
1532 caveats associated with a thread-based model for background job
1615
1533 execution. Type jobs.new? for details.
1616 IPython has a job manager, accessible via the 'jobs' object. You can
1534
1617 type jobs? to get more information about it, and use jobs.<TAB> to see
1535 You can check the status of all jobs with jobs.status().
1618 its attributes. All attributes not starting with an underscore are
1536
1619 meant for public use.
1537 The jobs variable is set by IPython into the Python builtin namespace.
1620
1538 If you ever declare a variable named 'jobs', you will shadow this name.
1621 In particular, look at the jobs.new() method, which is used to create
1539 You can either delete your global jobs variable to regain access to the
1622 new jobs. This magic %bg function is just a convenience wrapper
1540 job manager, or make a new name and assign it manually to the manager
1623 around jobs.new(), for expression-based jobs. If you want to create a
1541 (stored in IPython's namespace). For example, to assign the job manager
1624 new job with an explicit function object and arguments, you must call
1542 to the Jobs name, use:
1625 jobs.new() directly.
1543
1626
1544 Jobs = __builtins__.jobs
1627 The jobs.new docstring also describes in detail several important
1545
1628 caveats associated with a thread-based model for background job
1546
1629 execution. Type jobs.new? for details.
1547 %bookmark: Manage IPython's bookmark system.
1630
1548
1631 You can check the status of all jobs with jobs.status().
1549 %bookmark <name> - set bookmark to current dir %bookmark <name> <dir> -
1632
1550 set bookmark to <dir> %bookmark -l - list all bookmarks %bookmark -d
1633 The jobs variable is set by IPython into the Python builtin namespace.
1551 <name> - remove bookmark %bookmark -r - remove all bookmarks
1634 If you ever declare a variable named 'jobs', you will shadow this
1552
1635 name. You can either delete your global jobs variable to regain
1553 You can later on access a bookmarked folder with: %cd -b <name> or
1636 access to the job manager, or make a new name and assign it manually
1554 simply '%cd <name>' if there is no directory called <name> AND there is
1637 to the manager (stored in IPython's namespace). For example, to
1555 such a bookmark defined.
1638 assign the job manager to the Jobs name, use:
1556
1639
1557 Your bookmarks persist through IPython sessions, but they are associated
1640 Jobs = __builtins__.jobs
1558 with each profile.
1641
1559
1642 **%bookmark**::
1560
1643
1561 %cd: Change the current working directory.
1644 Manage IPython's bookmark system.
1562
1645
1563 This command automatically maintains an internal list of directories you
1646 %bookmark <name> - set bookmark to current dir
1564 visit during your IPython session, in the variable _dh. The command
1647 %bookmark <name> <dir> - set bookmark to <dir>
1565 %dhist shows this history nicely formatted. You can also do 'cd -<tab>'
1648 %bookmark -l - list all bookmarks
1566 to see directory history conveniently.
1649 %bookmark -d <name> - remove bookmark
1567
1650 %bookmark -r - remove all bookmarks
1568 Usage:
1651
1569
1652 You can later on access a bookmarked folder with:
1570 cd 'dir': changes to directory 'dir'.
1653 %cd -b <name>
1571
1654 or simply '%cd <name>' if there is no directory called <name> AND
1572 cd -: changes to the last visited directory.
1655 there is such a bookmark defined.
1573
1656
1574 cd -<n>: changes to the n-th directory in the directory history.
1657 Your bookmarks persist through IPython sessions, but they are
1575
1658 associated with each profile.
1576 cd -b <bookmark_name>: jump to a bookmark set by %bookmark (note: cd
1659
1577 <bookmark_name> is enough if there is no directory <bookmark_name>, but
1660 **%cd**::
1578 a bookmark with the name exists.) 'cd -b <tab>' allows you to
1661
1579 tab-complete bookmark names.
1662 Change the current working directory.
1580
1663
1581 Options:
1664 This command automatically maintains an internal list of directories
1582
1665 you visit during your IPython session, in the variable _dh. The
1583 -q: quiet. Do not print the working directory after the cd command is
1666 command %dhist shows this history nicely formatted. You can also
1584 executed. By default IPython's cd command does print this directory,
1667 do 'cd -<tab>' to see directory history conveniently.
1585 since the default prompts do not display path information.
1668
1586
1669 Usage:
1587 Note that !cd doesn't work for this purpose because the shell where
1670
1588 !command runs is immediately discarded after executing 'command'.
1671 cd 'dir': changes to directory 'dir'.
1589
1672
1590
1673 cd -: changes to the last visited directory.
1591 %color_info: Toggle color_info.
1674
1592
1675 cd -<n>: changes to the n-th directory in the directory history.
1593 The color_info configuration parameter controls whether colors are used
1676
1594 for displaying object details (by things like %psource, %pfile or the
1677 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
1595 '?' system). This function toggles this value with each call.
1678 (note: cd <bookmark_name> is enough if there is no
1596
1679 directory <bookmark_name>, but a bookmark with the name exists.)
1597 Note that unless you have a fairly recent pager (less works better than
1680 'cd -b <tab>' allows you to tab-complete bookmark names.
1598 more) in your system, using colored object information displays will not
1681
1599 work properly. Test it and see.
1682 Options:
1600
1683
1601
1684 -q: quiet. Do not print the working directory after the cd command is
1602 %colors: Switch color scheme for prompts, info system and exception
1685 executed. By default IPython's cd command does print this directory,
1603 handlers.
1686 since the default prompts do not display path information.
1604
1687
1605 Currently implemented schemes: NoColor, Linux, LightBG.
1688 Note that !cd doesn't work for this purpose because the shell where
1606
1689 !command runs is immediately discarded after executing 'command'.
1607 Color scheme names are not case-sensitive.
1690
1608
1691 **%clear**::
1609
1692
1610 %cpaste: Allows you to paste & execute a pre-formatted code block from
1693 Clear various data (e.g. stored history data)
1611 clipboard
1694
1612
1695 %clear out - clear output history
1613 You must terminate the block with '-' (two minus-signs) alone on the
1696 %clear in - clear input history
1614 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1697 %clear shadow_compress - Compresses shadow history (to speed up ipython)
1615 is the new sentinel for this operation)
1698 %clear shadow_nuke - permanently erase all entries in shadow history
1616
1699 %clear dhist - clear dir history
1617 The block is dedented prior to execution to enable execution of method
1700
1618 definitions. '>' and '+' characters at the beginning of a line are
1701 **%color_info**::
1619 ignored, to allow pasting directly from e-mails or diff files. The
1702
1620 executed block is also assigned to variable named 'pasted_block' for
1703 Toggle color_info.
1621 later editing with '%edit pasted_block'.
1704
1622
1705 The color_info configuration parameter controls whether colors are
1623 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1706 used for displaying object details (by things like %psource, %pfile or
1624 This assigns the pasted block to variable 'foo' as string, without
1707 the '?' system). This function toggles this value with each call.
1625 dedenting or executing it.
1708
1626
1709 Note that unless you have a fairly recent pager (less works better
1627 Do not be alarmed by garbled output on Windows (it's a readline bug).
1710 than more) in your system, using colored object information displays
1628 Just press enter and type - (and press enter again) and the block will
1711 will not work properly. Test it and see.
1629 be what was just pasted.
1712
1630
1713 **%colors**::
1631 IPython statements (magics, shell escapes) are not supported (yet).
1714
1632
1715 Switch color scheme for prompts, info system and exception handlers.
1633
1716
1634 %debug: Activate the interactive debugger in post-mortem mode.
1717 Currently implemented schemes: NoColor, Linux, LightBG.
1635
1718
1636 If an exception has just occurred, this lets you inspect its stack
1719 Color scheme names are not case-sensitive.
1637 frames interactively. Note that this will always work only on the last
1720
1638 traceback that occurred, so you must call this quickly after an
1721 **%cpaste**::
1639 exception that you wish to inspect has fired, because if another one
1722
1640 occurs, it clobbers the previous one.
1723 Allows you to paste & execute a pre-formatted code block from clipboard
1641
1724
1642 If you want IPython to automatically do this on every exception, see the
1725 You must terminate the block with '--' (two minus-signs) alone on the
1643 %pdb magic for more details.
1726 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
1644
1727 is the new sentinel for this operation)
1645
1728
1646 %dhist: Print your history of visited directories.
1729 The block is dedented prior to execution to enable execution of method
1647
1730 definitions. '>' and '+' characters at the beginning of a line are
1648 %dhist -> print full history
1731 ignored, to allow pasting directly from e-mails or diff files. The
1649 %dhist n -> print last n entries only
1732 executed block is also assigned to variable named 'pasted_block' for
1650 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)
1733 later editing with '%edit pasted_block'.
1651
1734
1652 This history is automatically maintained by the %cd command, and always
1735 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
1653 available as the global list variable _dh. You can use %cd -<n> to go to
1736 This assigns the pasted block to variable 'foo' as string, without
1654 directory number <n>.
1737 dedenting or executing it.
1655
1738
1656 Note that most of time, you should view directory history by entering cd
1739 Do not be alarmed by garbled output on Windows (it's a readline bug).
1657 -<TAB>.
1740 Just press enter and type -- (and press enter again) and the block
1658
1741 will be what was just pasted.
1659
1742
1660 %dirs: Return the current directory stack.
1743 IPython statements (magics, shell escapes) are not supported (yet).
1661
1744
1662
1745 **%debug**::
1663 %doctest_mode: Toggle doctest mode on and off.
1746
1664
1747 Activate the interactive debugger in post-mortem mode.
1665 This mode allows you to toggle the prompt behavior between normal
1748
1666 IPython prompts and ones that are as similar to the default IPython
1749 If an exception has just occurred, this lets you inspect its stack
1667 interpreter as possible.
1750 frames interactively. Note that this will always work only on the last
1668
1751 traceback that occurred, so you must call this quickly after an
1669 It also supports the pasting of code snippets that have leading '»>' and
1752 exception that you wish to inspect has fired, because if another one
1670 '...' prompts in them. This means that you can paste doctests from files
1753 occurs, it clobbers the previous one.
1671 or docstrings (even if they have leading whitespace), and the code will
1754
1672 execute correctly. You can then use '%history -tn' to see the translated
1755 If you want IPython to automatically do this on every exception, see
1673 history without line numbers; this will give you the input after removal
1756 the %pdb magic for more details.
1674 of all the leading prompts and whitespace, which can be pasted back into
1757
1675 an editor.
1758 **%dhist**::
1676
1759
1677 With these features, you can switch into this mode easily whenever you
1760 Print your history of visited directories.
1678 need to do testing and changes to doctests, without having to leave your
1761
1679 existing IPython session.
1762 %dhist -> print full history\
1680
1763 %dhist n -> print last n entries only\
1681
1764 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
1682 %ed: Alias to %edit.
1765
1683
1766 This history is automatically maintained by the %cd command, and
1684
1767 always available as the global list variable _dh. You can use %cd -<n>
1685 %edit: Bring up an editor and execute the resulting code.
1768 to go to directory number <n>.
1686
1769
1687 Usage: %edit [options] [args]
1770 Note that most of time, you should view directory history by entering
1688
1771 cd -<TAB>.
1689 %edit runs IPython's editor hook. The default version of this hook is
1772
1690 set to call the __IPYTHON__.rc.editor command. This is read from your
1773 **%dirs**::
1691 environment variable $EDITOR. If this isn't found, it will default to vi
1774
1692 under Linux/Unix and to notepad under Windows. See the end of this
1775 Return the current directory stack.
1693 docstring for how to change the editor hook.
1776
1694
1777 **%doctest_mode**::
1695 You can also set the value of this editor via the command line option
1778
1696 '-editor' or in your ipythonrc file. This is useful if you wish to use
1779 Toggle doctest mode on and off.
1697 specifically for IPython an editor different from your typical default
1780
1698 (and for Windows users who typically don't set environment variables).
1781 This mode allows you to toggle the prompt behavior between normal
1699
1782 IPython prompts and ones that are as similar to the default IPython
1700 This command allows you to conveniently edit multi-line code right in
1783 interpreter as possible.
1701 your IPython session.
1784
1702
1785 It also supports the pasting of code snippets that have leading '>>>'
1703 If called without arguments, %edit opens up an empty editor with a
1786 and '...' prompts in them. This means that you can paste doctests from
1704 temporary file and will execute the contents of this file when you close
1787 files or docstrings (even if they have leading whitespace), and the
1705 it (don't forget to save it!).
1788 code will execute correctly. You can then use '%history -tn' to see
1706
1789 the translated history without line numbers; this will give you the
1707 Options:
1790 input after removal of all the leading prompts and whitespace, which
1708
1791 can be pasted back into an editor.
1709 -n <number>: open the editor at a specified line number. By default, the
1792
1710 IPython editor hook uses the unix syntax 'editor +N filename', but you
1793 With these features, you can switch into this mode easily whenever you
1711 can configure this by providing your own modified hook if your favorite
1794 need to do testing and changes to doctests, without having to leave
1712 editor supports line-number specifications with a different syntax.
1795 your existing IPython session.
1713
1796
1714 -p: this will call the editor with the same data as the previous time it
1797 **%ed**::
1715 was used, regardless of how long ago (in your current session) it was.
1798
1716
1799 Alias to %edit.
1717 -r: use 'raw' input. This option only applies to input taken from the
1800
1718 user's history. By default, the 'processed' history is used, so that
1801 **%edit**::
1719 magics are loaded in their transformed version to valid Python. If this
1802
1720 option is given, the raw input as typed as the command line is used
1803 Bring up an editor and execute the resulting code.
1721 instead. When you exit the editor, it will be executed by IPython's own
1804
1722 processor.
1805 Usage:
1723
1806 %edit [options] [args]
1724 -x: do not execute the edited code immediately upon exit. This is mainly
1807
1725 useful if you are editing programs which need to be called with command
1808 %edit runs IPython's editor hook. The default version of this hook is
1726 line arguments, which you can then do using %run.
1809 set to call the __IPYTHON__.rc.editor command. This is read from your
1727
1810 environment variable $EDITOR. If this isn't found, it will default to
1728 Arguments:
1811 vi under Linux/Unix and to notepad under Windows. See the end of this
1729
1812 docstring for how to change the editor hook.
1730 If arguments are given, the following possibilites exist:
1813
1731
1814 You can also set the value of this editor via the command line option
1732 - The arguments are numbers or pairs of dash-separated numbers (like 1
1815 '-editor' or in your ipythonrc file. This is useful if you wish to use
1733 4-8 9). These are interpreted as lines of previous input to be loaded
1816 specifically for IPython an editor different from your typical default
1734 into the editor. The syntax is the same of the %macro command.
1817 (and for Windows users who typically don't set environment variables).
1735
1818
1736 - If the argument doesn't start with a number, it is evaluated as a
1819 This command allows you to conveniently edit multi-line code right in
1737 variable and its contents loaded into the editor. You can thus edit any
1820 your IPython session.
1738 string which contains python code (including the result of previous edits).
1821
1739
1822 If called without arguments, %edit opens up an empty editor with a
1740 - If the argument is the name of an object (other than a string),
1823 temporary file and will execute the contents of this file when you
1741 IPython will try to locate the file where it was defined and open the
1824 close it (don't forget to save it!).
1742 editor at the point where it is defined. You can use '%edit function' to
1825
1743 load an editor exactly at the point where 'function' is defined, edit it
1826
1744 and have the file be executed automatically.
1827 Options:
1745
1828
1746 If the object is a macro (see %macro for details), this opens up your
1829 -n <number>: open the editor at a specified line number. By default,
1747 specified editor with a temporary file containing the macro's data. Upon
1830 the IPython editor hook uses the unix syntax 'editor +N filename', but
1748 exit, the macro is reloaded with the contents of the file.
1831 you can configure this by providing your own modified hook if your
1749
1832 favorite editor supports line-number specifications with a different
1750 Note: opening at an exact line is only supported under Unix, and some
1833 syntax.
1751 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1834
1752 '+NUMBER' parameter necessary for this feature. Good editors like
1835 -p: this will call the editor with the same data as the previous time
1753 (X)Emacs, vi, jed, pico and joe all do.
1836 it was used, regardless of how long ago (in your current session) it
1754
1837 was.
1755 If the argument is not found as a variable, IPython will look for a
1838
1756 file with that name (adding .py if necessary) and load it into the
1839 -r: use 'raw' input. This option only applies to input taken from the
1757 editor. It will execute its contents with execfile() when you exit,
1840 user's history. By default, the 'processed' history is used, so that
1758 loading any code in the file into your interactive namespace.
1841 magics are loaded in their transformed version to valid Python. If
1759
1842 this option is given, the raw input as typed as the command line is
1760 After executing your code, %edit will return as output the code you
1843 used instead. When you exit the editor, it will be executed by
1761 typed in the editor (except when it was an existing file). This way you
1844 IPython's own processor.
1762 can reload the code in further invocations of %edit as a variable, via
1845
1763 _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the
1846 -x: do not execute the edited code immediately upon exit. This is
1764 output.
1847 mainly useful if you are editing programs which need to be called with
1765
1848 command line arguments, which you can then do using %run.
1766 Note that %edit is also available through the alias %ed.
1849
1767
1850
1768 This is an example of creating a simple function inside the editor and
1851 Arguments:
1769 then modifying it. First, start up the editor::
1852
1770
1853 If arguments are given, the following possibilites exist:
1771 In [1]: ed
1854
1772 Editing... done. Executing edited code...
1855 - The arguments are numbers or pairs of colon-separated numbers (like
1773 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1856 1 4:8 9). These are interpreted as lines of previous input to be
1774
1857 loaded into the editor. The syntax is the same of the %macro command.
1775 We can then call the function foo():
1858
1776
1859 - If the argument doesn't start with a number, it is evaluated as a
1777 In [2]: foo()
1860 variable and its contents loaded into the editor. You can thus edit
1778 foo() was defined in an editing session
1861 any string which contains python code (including the result of
1779
1862 previous edits).
1780 Now we edit foo. IPython automatically loads the editor with the
1863
1781 (temporary) file where foo() was previously defined:
1864 - If the argument is the name of an object (other than a string),
1782
1865 IPython will try to locate the file where it was defined and open the
1783 In [3]: ed foo
1866 editor at the point where it is defined. You can use `%edit function`
1784 Editing... done. Executing edited code...
1867 to load an editor exactly at the point where 'function' is defined,
1785
1868 edit it and have the file be executed automatically.
1786 And if we call foo() again we get the modified version:
1869
1787
1870 If the object is a macro (see %macro for details), this opens up your
1788 In [4]: foo()
1871 specified editor with a temporary file containing the macro's data.
1789 foo() has now been changed!
1872 Upon exit, the macro is reloaded with the contents of the file.
1790
1873
1791 Here is an example of how to edit a code snippet successive times. First
1874 Note: opening at an exact line is only supported under Unix, and some
1792 we call the editor:
1875 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1793
1876 '+NUMBER' parameter necessary for this feature. Good editors like
1794 In [8]: ed
1877 (X)Emacs, vi, jed, pico and joe all do.
1795 Editing... done. Executing edited code...
1878
1796 hello
1879 - If the argument is not found as a variable, IPython will look for a
1797 Out[8]: "print 'hello'\n"
1880 file with that name (adding .py if necessary) and load it into the
1798
1881 editor. It will execute its contents with execfile() when you exit,
1799 Now we call it again with the previous output (stored in _):
1882 loading any code in the file into your interactive namespace.
1800
1883
1801 In [9]: ed _
1884 After executing your code, %edit will return as output the code you
1802 Editing... done. Executing edited code...
1885 typed in the editor (except when it was an existing file). This way
1803 hello world
1886 you can reload the code in further invocations of %edit as a variable,
1804 Out[9]: "print 'hello world'\n"
1887 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1805
1888 the output.
1806 Now we call it with the output #8 (stored in _8, also as Out[8]):
1889
1807
1890 Note that %edit is also available through the alias %ed.
1808 In [10]: ed _8
1891
1809 Editing... done. Executing edited code...
1892 This is an example of creating a simple function inside the editor and
1810 hello again
1893 then modifying it. First, start up the editor:
1811 Out[10]: "print 'hello again'\n"
1894
1812
1895 In [1]: ed\
1813 Changing the default editor hook:
1896 Editing... done. Executing edited code...\
1814
1897 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
1815 If you wish to write your own editor hook, you can put it in a
1898
1816 configuration file which you load at startup time. The default hook is
1899 We can then call the function foo():
1817 defined in the IPython.hooks module, and you can use that as a starting
1900
1818 example for further modifications. That file also has general
1901 In [2]: foo()\
1819 instructions on how to set a new hook for use once you've defined it.
1902 foo() was defined in an editing session
1820
1903
1821
1904 Now we edit foo. IPython automatically loads the editor with the
1822 %env: List environment variables.
1905 (temporary) file where foo() was previously defined:
1823
1906
1824
1907 In [3]: ed foo\
1825 %exit: Exit IPython, confirming if configured to do so.
1908 Editing... done. Executing edited code...
1826
1909
1827 You can configure whether IPython asks for confirmation upon exit by
1910 And if we call foo() again we get the modified version:
1828 setting the confirm_exit flag in the ipythonrc file.
1911
1829
1912 In [4]: foo()\
1830
1913 foo() has now been changed!
1831 %logoff: Temporarily stop logging.
1914
1832
1915 Here is an example of how to edit a code snippet successive
1833 You must have previously started logging.
1916 times. First we call the editor:
1834
1917
1835
1918 In [8]: ed\
1836 %logon: Restart logging.
1919 Editing... done. Executing edited code...\
1837
1920 hello\
1838 This function is for restarting logging which you've temporarily stopped
1921 Out[8]: "print 'hello'\n"
1839 with %logoff. For starting logging for the first time, you must use the
1922
1840 %logstart function, which allows you to specify an optional log filename.
1923 Now we call it again with the previous output (stored in _):
1841
1924
1842
1925 In [9]: ed _\
1843 %logstart: Start logging anywhere in a session.
1926 Editing... done. Executing edited code...\
1844
1927 hello world\
1845 %logstart [-o|-r|-t] [log_name [log_mode]]
1928 Out[9]: "print 'hello world'\n"
1846
1929
1847 If no name is given, it defaults to a file named 'ipython_log.py' in
1930 Now we call it with the output #8 (stored in _8, also as Out[8]):
1848 your current directory, in 'rotate' mode (see below).
1931
1849
1932 In [10]: ed _8\
1850 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1933 Editing... done. Executing edited code...\
1851 history up to that point and then continues logging.
1934 hello again\
1852
1935 Out[10]: "print 'hello again'\n"
1853 %logstart takes a second optional parameter: logging mode. This can be
1936
1854 one of (note that the modes are given unquoted):
1937
1855 append: well, that says it.
1938 Changing the default editor hook:
1856 backup: rename (if exists) to name and start name.
1939
1857 global: single logfile in your home dir, appended to.
1940 If you wish to write your own editor hook, you can put it in a
1858 over : overwrite existing log.
1941 configuration file which you load at startup time. The default hook
1859 rotate: create rotating logs name.1 , name.2 , etc.
1942 is defined in the IPython.hooks module, and you can use that as a
1860
1943 starting example for further modifications. That file also has
1861 Options:
1944 general instructions on how to set a new hook for use once you've
1862
1945 defined it.
1863 -o: log also IPython's output. In this mode, all commands which generate
1946
1864 an Out[NN] prompt are recorded to the logfile, right after their
1947 **%env**::
1865 corresponding input line. The output lines are always prepended with a
1948
1866 '#[Out]# ' marker, so that the log remains valid Python code.
1949 List environment variables.
1867
1950
1868 Since this marker is always the same, filtering only the output from a
1951 **%exit**::
1869 log is very easy, using for example a simple awk call:
1952
1870
1953 Exit IPython, confirming if configured to do so.
1871 awk -F'#
1954
1872
1955 You can configure whether IPython asks for confirmation upon exit by
1873 \begin{displaymath}Out\end{displaymath}
1956 setting the confirm_exit flag in the ipythonrc file.
1874
1957
1875 # ' 'if($2) print $2' ipython_log.py
1958 **%hist**::
1876
1959
1877 -r: log 'raw' input. Normally, IPython's logs contain the processed
1960 Alternate name for %history.
1878 input, so that user lines are logged in their final form, converted into
1961
1879 valid Python. For example, %Exit is logged as '_ip.magic("Exit"). If the
1962 **%history**::
1880 -r flag is given, all input is logged exactly as typed, with no
1963
1881 transformations applied.
1964 Print input history (_i<n> variables), with most recent last.
1882
1965
1883 -t: put timestamps before each input line logged (these are put in
1966 %history -> print at most 40 inputs (some may be multi-line)\
1884 comments).
1967 %history n -> print at most n inputs\
1885
1968 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1886
1969
1887 %logstate: Print the status of the logging system.
1970 Each input's number <n> is shown, and is accessible as the
1888
1971 automatically generated variable _i<n>. Multi-line statements are
1889
1972 printed starting at a new line for easy copy/paste.
1890 %logstop: Fully stop logging and close log file.
1973
1891
1974
1892 In order to start logging again, a new %logstart call needs to be made,
1975 Options:
1893 possibly (though not necessarily) with a new filename, mode and other
1976
1894 options.
1977 -n: do NOT print line numbers. This is useful if you want to get a
1895
1978 printout of many lines which can be directly pasted into a text
1896
1979 editor.
1897 %lsmagic: List currently available magic functions.
1980
1898
1981 This feature is only available if numbered prompts are in use.
1899
1982
1900 %macro: Define a set of input lines as a macro for future re-execution.
1983 -t: (default) print the 'translated' history, as IPython understands it.
1901
1984 IPython filters your input and converts it all into valid Python source
1902 Usage:
1985 before executing it (things like magics or aliases are turned into
1903 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1986 function calls, for example). With this option, you'll see the native
1904
1987 history instead of the user-entered version: '%cd /' will be seen as
1905 Options:
1988 '_ip.magic("%cd /")' instead of '%cd /'.
1906
1989
1907 -r: use 'raw' input. By default, the 'processed' history is used, so
1990 -r: print the 'raw' history, i.e. the actual commands you typed.
1908 that magics are loaded in their transformed version to valid Python. If
1991
1909 this option is given, the raw input as typed as the command line is used
1992 -g: treat the arg as a pattern to grep for in (full) history.
1910 instead.
1993 This includes the "shadow history" (almost all commands ever written).
1911
1994 Use '%hist -g' to show full shadow history (may be very long).
1912 This will define a global variable called 'name' which is a string made
1995 In shadow history, every index nuwber starts with 0.
1913 of joining the slices and lines you specify (n1,n2,... numbers above)
1996
1914 from your input history into a single string. This variable acts like an
1997 -f FILENAME: instead of printing the output to the screen, redirect it to
1915 automatic function which re-executes those lines as if you had typed
1998 the given file. The file is always overwritten, though IPython asks for
1916 them. You just type 'name' at the prompt and the code executes.
1999 confirmation first if it already exists.
1917
2000
1918 The notation for indicating number ranges is: n1-n2 means 'use line
2001 **%logoff**::
1919 numbers n1,...n2' (the endpoint is included). That is, '5-7' means using
2002
1920 the lines numbered 5,6 and 7.
2003 Temporarily stop logging.
1921
2004
1922 Note: as a 'hidden' feature, you can also use traditional python slice
2005 You must have previously started logging.
1923 notation, where N:M means numbers N through M-1.
2006
1924
2007 **%logon**::
1925 For example, if your history contains (%hist prints it):
2008
1926
2009 Restart logging.
1927 44: x=1
2010
1928 45: y=3
2011 This function is for restarting logging which you've temporarily
1929 46: z=x+y
2012 stopped with %logoff. For starting logging for the first time, you
1930 47: print x
2013 must use the %logstart function, which allows you to specify an
1931 48: a=5
2014 optional log filename.
1932 49: print 'x',x,'y',y
2015
1933
2016 **%logstart**::
1934 you can create a macro with lines 44 through 47 (included) and line 49
2017
1935 called my_macro with:
2018 Start logging anywhere in a session.
1936
2019
1937 In [51]: %macro my_macro 44-47 49
2020 %logstart [-o|-r|-t] [log_name [log_mode]]
1938
2021
1939 Now, typing 'my_macro' (without quotes) will re-execute all this code in
2022 If no name is given, it defaults to a file named 'ipython_log.py' in your
1940 one pass.
2023 current directory, in 'rotate' mode (see below).
1941
2024
1942 You don't need to give the line-numbers in order, and any given line
2025 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1943 number can appear multiple times. You can assemble macros with any lines
2026 history up to that point and then continues logging.
1944 from your input history in any order.
2027
1945
2028 %logstart takes a second optional parameter: logging mode. This can be one
1946 The macro is a simple object which holds its value in an attribute, but
2029 of (note that the modes are given unquoted):\
1947 IPython's display system checks for macros and executes them as code
2030 append: well, that says it.\
1948 instead of printing them when you type their name.
2031 backup: rename (if exists) to name~ and start name.\
1949
2032 global: single logfile in your home dir, appended to.\
1950 You can view a macro's contents by explicitly printing it with:
2033 over : overwrite existing log.\
1951
2034 rotate: create rotating logs name.1~, name.2~, etc.
1952 'print macro_name'.
2035
1953
2036 Options:
1954 For one-off cases which DON'T contain magic function calls in them you
2037
1955 can obtain similar results by explicitly executing slices from your
2038 -o: log also IPython's output. In this mode, all commands which
1956 input history with:
2039 generate an Out[NN] prompt are recorded to the logfile, right after
1957
2040 their corresponding input line. The output lines are always
1958 In [60]: exec In[44:48]+In[49]
2041 prepended with a '#[Out]# ' marker, so that the log remains valid
1959
2042 Python code.
1960
2043
1961 %magic: Print information about the magic function system.
2044 Since this marker is always the same, filtering only the output from
1962
2045 a log is very easy, using for example a simple awk call:
1963
2046
1964 %page: Pretty print the object and display it through a pager.
2047 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1965
2048
1966 %page [options] OBJECT
2049 -r: log 'raw' input. Normally, IPython's logs contain the processed
1967
2050 input, so that user lines are logged in their final form, converted
1968 If no object is given, use _ (last output).
2051 into valid Python. For example, %Exit is logged as
1969
2052 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1970 Options:
2053 exactly as typed, with no transformations applied.
1971
2054
1972 -r: page str(object), don't pretty-print it.
2055 -t: put timestamps before each input line logged (these are put in
1973
2056 comments).
1974
2057
1975 %pdb: Control the automatic calling of the pdb interactive debugger.
2058 **%logstate**::
1976
2059
1977 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
2060 Print the status of the logging system.
1978 argument it works as a toggle.
2061
1979
2062 **%logstop**::
1980 When an exception is triggered, IPython can optionally call the
2063
1981 interactive pdb debugger after the traceback printout. %pdb toggles this
2064 Fully stop logging and close log file.
1982 feature on and off.
2065
1983
2066 In order to start logging again, a new %logstart call needs to be made,
1984 The initial state of this feature is set in your ipythonrc configuration
2067 possibly (though not necessarily) with a new filename, mode and other
1985 file (the variable is called 'pdb').
2068 options.
1986
2069
1987 If you want to just activate the debugger AFTER an exception has fired,
2070 **%lsmagic**::
1988 without having to type '%pdb on' and rerunning your code, you can use
2071
1989 the %debug magic.
2072 List currently available magic functions.
1990
2073
1991
2074 **%macro**::
1992 %pdef: Print the definition header for any callable object.
2075
1993
2076 Define a set of input lines as a macro for future re-execution.
1994 If the object is a class, print the constructor information.
2077
1995
2078 Usage:\
1996
2079 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1997 %pdoc: Print the docstring for an object.
2080
1998
2081 Options:
1999 If the given object is a class, it will print both the class and the
2082
2000 constructor docstrings.
2083 -r: use 'raw' input. By default, the 'processed' history is used,
2001
2084 so that magics are loaded in their transformed version to valid
2002
2085 Python. If this option is given, the raw input as typed as the
2003 %pfile: Print (or run through pager) the file where an object is defined.
2086 command line is used instead.
2004
2087
2005 The file opens at the line where the object definition begins. IPython
2088 This will define a global variable called `name` which is a string
2006 will honor the environment variable PAGER if set, and otherwise will do
2089 made of joining the slices and lines you specify (n1,n2,... numbers
2007 its best to print the file in a convenient form.
2090 above) from your input history into a single string. This variable
2008
2091 acts like an automatic function which re-executes those lines as if
2009 If the given argument is not an object currently defined, IPython will
2092 you had typed them. You just type 'name' at the prompt and the code
2010 try to interpret it as a filename (automatically adding a .py extension
2093 executes.
2011 if needed). You can thus use %pfile as a syntax highlighting code viewer.
2094
2012
2095 The notation for indicating number ranges is: n1-n2 means 'use line
2013
2096 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2014 %pinfo: Provide detailed information about an object.
2097 using the lines numbered 5,6 and 7.
2015
2098
2016 '%pinfo object' is just a synonym for object? or ?object.
2099 Note: as a 'hidden' feature, you can also use traditional python slice
2017
2100 notation, where N:M means numbers N through M-1.
2018
2101
2019 %popd: Change to directory popped off the top of the stack.
2102 For example, if your history contains (%hist prints it):
2020
2103
2021
2104 44: x=1\
2022 %profile: Print your currently active IPyhton profile.
2105 45: y=3\
2023
2106 46: z=x+y\
2024
2107 47: print x\
2025 %prun: Run a statement through the python code profiler.
2108 48: a=5\
2026
2109 49: print 'x',x,'y',y\
2027 Usage:
2110
2028 %prun [options] statement
2111 you can create a macro with lines 44 through 47 (included) and line 49
2029
2112 called my_macro with:
2030 The given statement (which doesn't require quote marks) is run via the
2113
2031 python profiler in a manner similar to the profile.run() function.
2114 In [51]: %macro my_macro 44-47 49
2032 Namespaces are internally managed to work correctly; profile.run cannot
2115
2033 be used in IPython because it makes certain assumptions about namespaces
2116 Now, typing `my_macro` (without quotes) will re-execute all this code
2034 which do not hold under IPython.
2117 in one pass.
2035
2118
2036 Options:
2119 You don't need to give the line-numbers in order, and any given line
2037
2120 number can appear multiple times. You can assemble macros with any
2038 -l <limit>: you can place restrictions on what or how much of the
2121 lines from your input history in any order.
2039 profile gets printed. The limit value can be:
2122
2040
2123 The macro is a simple object which holds its value in an attribute,
2041 * A string: only information for function names containing this string
2124 but IPython's display system checks for macros and executes them as
2042 is printed.
2125 code instead of printing them when you type their name.
2043
2126
2044 * An integer: only these many lines are printed.
2127 You can view a macro's contents by explicitly printing it with:
2045
2128
2046 * A float (between 0 and 1): this fraction of the report is printed (for
2129 'print macro_name'.
2047 example, use a limit of 0.4 to see the topmost 40% only).
2130
2048
2131 For one-off cases which DON'T contain magic function calls in them you
2049 You can combine several limits with repeated use of the option. For
2132 can obtain similar results by explicitly executing slices from your
2050 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2133 input history with:
2051 information about class constructors.
2134
2052
2135 In [60]: exec In[44:48]+In[49]
2053 -r: return the pstats.Stats object generated by the profiling. This
2136
2054 object has all the information about the profile in it, and you can
2137 **%magic**::
2055 later use it for further analysis or in other functions.
2056
2057 -s <key>: sort profile by given key. You can provide more than one key
2058 by using the option several times: '-s key1 -s key2 -s key3...'. The
2059 default sorting key is 'time'.
2060
2061 The following is copied verbatim from the profile documentation
2062 referenced below:
2063
2064 When more than one key is provided, additional keys are used as
2065 secondary criteria when the there is equality in all keys selected
2066 before them.
2067
2068 Abbreviations can be used for any key names, as long as the abbreviation
2069 is unambiguous. The following are the keys currently defined:
2070
2071 Valid Arg Meaning
2072 "calls" call count
2073 "cumulative" cumulative time
2074 "file" file name
2075 "module" file name
2076 "pcalls" primitive call count
2077 "line" line number
2078 "name" function name
2079 "nfl" name/file/line
2080 "stdname" standard name
2081 "time" internal time
2082
2083 Note that all sorts on statistics are in descending order (placing most
2084 time consuming items first), where as name, file, and line number
2085 searches are in ascending order (i.e., alphabetical). The subtle
2086 distinction between "nfl" and "stdname" is that the standard name is a
2087 sort of the name as printed, which means that the embedded line numbers
2088 get compared in an odd way. For example, lines 3, 20, and 40 would (if
2089 the file names were the same) appear in the string order "20" "3" and
2090 "40". In contrast, "nfl" does a numeric compare of the line numbers. In
2091 fact, sort_stats("nfl") is the same as sort_stats("name", "file", "line").
2092
2093 -T <filename>: save profile results as shown on screen to a text file.
2094 The profile is still shown on screen.
2095
2096 -D <filename>: save (via dump_stats) profile statistics to given
2097 filename. This data is in a format understod by the pstats module, and
2098 is generated by a call to the dump_stats() method of profile objects.
2099 The profile is still shown on screen.
2100
2101 If you want to run complete programs under the profiler's control, use
2102 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2103 contains profiler specific options as described here.
2104
2105 You can read the complete documentation for the profile module with:
2106 In [1]: import profile; profile.help()
2107
2108
2109 %psearch: Search for object in namespaces by wildcard.
2110
2111 %psearch [options] PATTERN [OBJECT TYPE]
2112
2113 Note: ? can be used as a synonym for %psearch, at the beginning or at
2114 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2115 rest of the command line must be unchanged (options come first), so for
2116 example the following forms are equivalent
2117
2118 %psearch -i a* function -i a* function? ?-i a* function
2119
2120 Arguments:
2121
2122 PATTERN
2123
2124 where PATTERN is a string containing * as a wildcard similar to its use
2125 in a shell. The pattern is matched in all namespaces on the search path.
2126 By default objects starting with a single _ are not matched, many
2127 IPython generated objects have a single underscore. The default is case
2128 insensitive matching. Matching is also done on the attributes of objects
2129 and not only on the objects in a module.
2130
2131 [OBJECT TYPE]
2132
2133 Is the name of a python type from the types module. The name is given in
2134 lowercase without the ending type, ex. StringType is written string. By
2135 adding a type here only objects matching the given type are matched.
2136 Using all here makes the pattern match all types (this is the default).
2137
2138 Options:
2139
2140 -a: makes the pattern match even objects whose names start with a single
2141 underscore. These names are normally ommitted from the search.
2142
2143 -i/-c: make the pattern case insensitive/sensitive. If neither of these
2144 options is given, the default is read from your ipythonrc file. The
2145 option name which sets this value is 'wildcards_case_sensitive'. If this
2146 option is not specified in your ipythonrc file, IPython's internal
2147 default is to do a case sensitive search.
2148
2149 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2150 specifiy can be searched in any of the following namespaces: 'builtin',
2151 'user', 'user_global','internal', 'alias', where 'builtin' and 'user'
2152 are the search defaults. Note that you should not use quotes when
2153 specifying namespaces.
2154
2155 'Builtin' contains the python module builtin, 'user' contains all user
2156 data, 'alias' only contain the shell aliases and no python objects,
2157 'internal' contains objects used by IPython. The 'user_global' namespace
2158 is only used by embedded IPython instances, and it contains module-level
2159 globals. You can add namespaces to the search with -s or exclude them
2160 with -e (these options can be given more than once).
2161
2162 Examples:
2163
2164 %psearch a* -> objects beginning with an a %psearch -e builtin a* ->
2165 objects NOT in the builtin space starting in a %psearch a* function ->
2166 all functions beginning with an a %psearch re.e* -> objects beginning
2167 with an e in module re %psearch r*.e* -> objects that start with e in
2168 modules starting in r %psearch r*.* string -> all strings in modules
2169 beginning with r
2170
2171 Case sensitve search:
2172
2173 %psearch -c a* list all object beginning with lower case a
2174
2175 Show objects beginning with a single _:
2176
2177 %psearch -a _* list objects beginning with a single underscore
2178
2179
2180 %psource: Print (or run through pager) the source code for an object.
2181
2182
2183 %pushd: Place the current dir on stack and change directory.
2184
2185 Usage:
2186 %pushd ['dirname']
2187
2188
2189 %pwd: Return the current working directory path.
2190
2191
2192 %pycat: Show a syntax-highlighted file through a pager.
2193
2194 This magic is similar to the cat utility, but it will assume the file to
2195 be Python source and will show it with syntax highlighting.
2196
2197
2198 %quickref: Show a quick reference sheet
2199
2200
2201 %quit: Exit IPython, confirming if configured to do so (like %exit)
2202
2203
2204 %r: Repeat previous input.
2205
2206 Note: Consider using the more powerfull %rep instead!
2207
2208 If given an argument, repeats the previous command which starts with the
2209 same string, otherwise it just repeats the previous input.
2210
2211 Shell escaped commands (with ! as first character) are not recognized by
2212 this system, only pure python code and magic commands.
2213
2214
2215 %rehashx: Update the alias table with all executable files in $PATH.
2216
2217 This version explicitly checks that every entry in $PATH is a file with
2218 execute access (os.X_OK), so it is much slower than %rehash.
2219
2220 Under Windows, it checks executability as a match agains a ``|``-separated
2221 string of extensions, stored in the IPython config variable
2222 win_exec_ext. This defaults to ``exe|com|bat``.
2223
2224 This function also resets the root module cache of module completer,
2225 used on slow filesystems.
2226
2227
2228 %reset: Resets the namespace by removing all names defined by the user.
2229
2230 Input/Output history are left around in case you need them.
2231
2232
2233 %run: Run the named file inside IPython as a program.
2234
2235 Usage:
2236 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2237
2238 Parameters after the filename are passed as command-line arguments to
2239 the program (put in sys.argv). Then, control returns to IPython's prompt.
2240
2241 This is similar to running at a system prompt:
2242 $ python file args
2243 but with the advantage of giving you IPython's tracebacks, and of
2244 loading all variables into your interactive namespace for further use
2245 (unless -p is used, see below).
2246
2247 The file is executed in a namespace initially consisting only of
2248 __name__=='__main__' and sys.argv constructed as indicated. It thus sees
2249 its environment as if it were being run as a stand-alone program (except
2250 for sharing global objects such as previously imported modules). But
2251 after execution, the IPython interactive namespace gets updated with all
2252 variables defined in the program (except for __name__ and sys.argv).
2253 This allows for very convenient loading of code for interactive work,
2254 while giving each program a 'clean sheet' to run in.
2255
2256 Options:
2257
2258 -n: __name__ is NOT set to '__main__', but to the running file's name
2259 without extension (as python does under import). This allows running
2260 scripts and reloading the definitions in them without calling code
2261 protected by an ' if __name__ == "__main__" ' clause.
2262
2263 -i: run the file in IPython's namespace instead of an empty one. This is
2264 useful if you are experimenting with code written in a text editor which
2265 depends on variables defined interactively.
2266
2267 -e: ignore sys.exit() calls or SystemExit exceptions in the script being
2268 run. This is particularly useful if IPython is being used to run
2269 unittests, which always exit with a sys.exit() call. In such cases you
2270 are interested in the output of the test results, not in seeing a
2271 traceback of the unittest module.
2272
2273 -t: print timing information at the end of the run. IPython will give
2274 you an estimated CPU time consumption for your script, which under Unix
2275 uses the resource module to avoid the wraparound problems of
2276 time.clock(). Under Unix, an estimate of time spent on system tasks is
2277 also given (for Windows platforms this is reported as 0.0).
2278
2279 If -t is given, an additional -N<N> option can be given, where <N> must
2280 be an integer indicating how many times you want the script to run. The
2281 final timing report will include total and per run results.
2282
2283 For example (testing the script uniq_stable.py):
2284
2285 In [1]: run -t uniq_stable
2286
2287 IPython CPU timings (estimated):
2288 User : 0.19597 s.
2289 System: 0.0 s.
2290
2291 In [2]: run -t -N5 uniq_stable
2292
2293 IPython CPU timings (estimated):
2294 Total runs performed: 5
2295 Times : Total Per run
2296 User : 0.910862 s, 0.1821724 s.
2297 System: 0.0 s, 0.0 s.
2298
2299 -d: run your program under the control of pdb, the Python debugger. This
2300 allows you to execute your program step by step, watch variables, etc.
2301 Internally, what IPython does is similar to calling:
2302
2303 pdb.run('execfile("YOURFILENAME")')
2304
2305 with a breakpoint set on line 1 of your file. You can change the line
2306 number for this automatic breakpoint to be <N> by using the -bN option
2307 (where N must be an integer). For example:
2308
2309 %run -d -b40 myscript
2310
2311 will set the first breakpoint at line 40 in myscript.py. Note that the
2312 first breakpoint must be set on a line which actually does something
2313 (not a comment or docstring) for it to stop execution.
2314
2315 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2316 first enter 'c' (without qoutes) to start execution up to the first
2317 breakpoint.
2318
2319 Entering 'help' gives information about the use of the debugger. You can
2320 easily see pdb's full documentation with "import pdb;pdb.help()" at a
2321 prompt.
2322
2323 -p: run program under the control of the Python profiler module (which
2324 prints a detailed report of execution times, function calls, etc).
2325
2326 You can pass other options after -p which affect the behavior of the
2327 profiler itself. See the docs for %prun for details.
2328
2329 In this mode, the program's variables do NOT propagate back to the
2330 IPython interactive namespace (because they remain in the namespace
2331 where the profiler executes them).
2332
2333 Internally this triggers a call to %prun, see its documentation for
2334 details on the options available specifically for profiling.
2335
2336 There is one special usage for which the text above doesn't apply: if
2337 the filename ends with .ipy, the file is run as ipython script, just as
2338 if the commands were written on IPython prompt.
2339
2340
2341 %runlog: Run files as logs.
2342
2343 Usage:
2344 %runlog file1 file2 ...
2345
2346 Run the named files (treating them as log files) in sequence inside the
2347 interpreter, and return to the prompt. This is much slower than %run
2348 because each line is executed in a try/except block, but it allows
2349 running files with syntax errors in them.
2350
2351 Normally IPython will guess when a file is one of its own logfiles, so
2352 you can typically use %run even for logs. This shorthand allows you to
2353 force any file to be treated as a log file.
2354
2355
2356 %save: Save a set of lines to a given filename.
2357
2358 Usage:
2359 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2360
2361 Options:
2362
2363 -r: use 'raw' input. By default, the 'processed' history is used, so
2364 that magics are loaded in their transformed version to valid Python. If
2365 this option is given, the raw input as typed as the command line is used
2366 instead.
2367
2368 This function uses the same syntax as %macro for line extraction, but
2369 instead of creating a macro it saves the resulting string to the
2370 filename you specify.
2371
2372 It adds a '.py' extension to the file if you don't do so yourself, and
2373 it asks for confirmation before overwriting existing files.
2374
2375
2376 %sc: Shell capture - execute a shell command and capture its output.
2377
2378 DEPRECATED. Suboptimal, retained for backwards compatibility.
2379
2380 You should use the form 'var = !command' instead. Example:
2381
2382 "%sc -l myfiles = ls " should now be written as
2383
2384 "myfiles = !ls "
2385
2386 myfiles.s, myfiles.l and myfiles.n still apply as documented below.
2387
2388 - %sc [options] varname=command
2389
2390 IPython will run the given command using commands.getoutput(), and will
2391 then update the user's interactive namespace with a variable called
2392 varname, containing the value of the call. Your command can contain
2393 shell wildcards, pipes, etc.
2394
2395 The '=' sign in the syntax is mandatory, and the variable name you
2396 supply must follow Python's standard conventions for valid names.
2397
2398 (A special format without variable name exists for internal use)
2399
2400 Options:
2401
2402 -l: list output. Split the output on newlines into a list before
2403 assigning it to the given variable. By default the output is stored as a
2404 single string.
2405
2406 -v: verbose. Print the contents of the variable.
2407
2408 In most cases you should not need to split as a list, because the
2409 returned value is a special type of string which can automatically
2410 provide its contents either as a list (split on newlines) or as a
2411 space-separated string. These are convenient, respectively, either for
2412 sequential processing or to be passed to a shell command.
2413
2414 For example:
2415
2416 # Capture into variable a In [9]: sc a=ls *py
2417
2418 # a is a string with embedded newlines In [10]: a Out[10]: 'setup.py
2419 win32_manual_post_install.py'
2420
2421 # which can be seen as a list: In [11]: a.l Out[11]: ['setup.py',
2422 'win32_manual_post_install.py']
2423
2424 # or as a whitespace-separated string: In [12]: a.s Out[12]: 'setup.py
2425 win32_manual_post_install.py'
2426
2427 # a.s is useful to pass as a single command line: In [13]: !wc -l $a.s
2428 146 setup.py 130 win32_manual_post_install.py 276 total
2429
2430 # while the list form is useful to loop over: In [14]: for f in a.l:
2431 ....: !wc -l $f ....: 146 setup.py 130 win32_manual_post_install.py
2432
2433 Similiarly, the lists returned by the -l option are also special, in the
2434 sense that you can equally invoke the .s attribute on them to
2435 automatically get a whitespace-separated string from their contents:
2436
2437 In [1]: sc -l b=ls *py
2438
2439 In [2]: b Out[2]: ['setup.py', 'win32_manual_post_install.py']
2440
2441 In [3]: b.s Out[3]: 'setup.py win32_manual_post_install.py'
2442
2443 In summary, both the lists and strings used for ouptut capture have the
2444 following special attributes:
2445
2446 .l (or .list) : value as list. .n (or .nlstr): value as
2447 newline-separated string. .s (or .spstr): value as space-separated string.
2448
2449
2450 %sx: Shell execute - run a shell command and capture its output.
2451
2452 %sx command
2453
2454 IPython will run the given command using commands.getoutput(), and
2455 return the result formatted as a list (split on '\n'). Since the output
2456 is _returned_, it will be stored in ipython's regular output cache
2457 Out[N] and in the '_N' automatic variables.
2458
2459 Notes:
2460
2461 1) If an input line begins with '!!', then %sx is automatically invoked.
2462 That is, while: !ls causes ipython to simply issue system('ls'), typing
2463 !!ls is a shorthand equivalent to: %sx ls
2464
2465 2) %sx differs from %sc in that %sx automatically splits into a list,
2466 like '%sc -l'. The reason for this is to make it as easy as possible to
2467 process line-oriented shell output via further python commands. %sc is
2468 meant to provide much finer control, but requires more typing.
2469
2470 3) Just like %sc -l, this is a list with special attributes:
2471
2472 .l (or .list) : value as list. .n (or .nlstr): value as
2473 newline-separated string. .s (or .spstr): value as whitespace-separated
2474 string.
2475
2476 This is very useful when trying to use such lists as arguments to system
2477 commands.
2478
2479
2480 %system_verbose: Set verbose printing of system calls.
2481
2482 If called without an argument, act as a toggle
2483
2484
2485 %time: Time execution of a Python statement or expression.
2486
2487 The CPU and wall clock times are printed, and the value of the
2488 expression (if any) is returned. Note that under Win32, system time is
2489 always reported as 0, since it can not be measured.
2490
2491 This function provides very basic timing functionality. In Python 2.3,
2492 the timeit module offers more control and sophistication, so this could
2493 be rewritten to use it (patches welcome).
2494
2495 Some examples:
2496
2497 In [1]: time 2**128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2498 Wall time: 0.00 Out[1]: 340282366920938463463374607431768211456L
2499
2500 In [2]: n = 1000000
2501
2502 In [3]: time sum(range(n)) CPU times: user 1.20 s, sys: 0.05 s, total:
2503 1.25 s Wall time: 1.37 Out[3]: 499999500000L
2504
2505 In [4]: time print 'hello world' hello world CPU times: user 0.00 s,
2506 sys: 0.00 s, total: 0.00 s Wall time: 0.00
2507
2508 Note that the time needed by Python to compile the given expression will
2509 be reported if it is more than 0.1s. In this example, the actual
2510 exponentiation is done by Python at compilation time, so while the
2511 expression can take a noticeable amount of time to compute, that time is
2512 purely due to the compilation:
2513
2514 In [5]: time 3**9999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2515 Wall time: 0.00 s
2516
2517 In [6]: time 3**999999; CPU times: user 0.00 s, sys: 0.00 s, total: 0.00
2518 s Wall time: 0.00 s Compiler : 0.78 s
2519
2520
2521 %timeit: Time execution of a Python statement or expression
2522
2523 Usage:
2524 %timeit [-n<N> -r<R> [-t|-c]] statement
2525
2526 Time execution of a Python statement or expression using the timeit module.
2527
2528 Options: -n<N>: execute the given statement <N> times in a loop. If this
2529 value is not given, a fitting value is chosen.
2530
2531 -r<R>: repeat the loop iteration <R> times and take the best result.
2532 Default: 3
2533
2534 -t: use time.time to measure the time, which is the default on Unix.
2535 This function measures wall time.
2536
2537 -c: use time.clock to measure the time, which is the default on Windows
2538 and measures wall time. On Unix, resource.getrusage is used instead and
2539 returns the CPU user time.
2540
2541 -p<P>: use a precision of <P> digits to display the timing result.
2542 Default: 3
2543
2544 Examples:
2545 In [1]: %timeit pass 10000000 loops, best of 3: 53.3 ns per loop
2546
2547 In [2]: u = None
2548
2549 In [3]: %timeit u is None 10000000 loops, best of 3: 184 ns per loop
2550
2551 In [4]: %timeit -r 4 u == None 1000000 loops, best of 4: 242 ns per loop
2552
2553 In [5]: import time
2554
2555 In [6]: %timeit -n1 time.sleep(2) 1 loops, best of 3: 2 s per loop
2556
2557 The times reported by %timeit will be slightly higher than those
2558 reported by the timeit.py script when variables are accessed. This is
2559 due to the fact that %timeit executes the statement in the namespace of
2560 the shell, compared with timeit.py, which uses a single setup statement
2561 to import function or create variables. Generally, the bias does not
2562 matter as long as results from timeit.py are not mixed with those from
2563 %timeit.
2564
2565
2566 %unalias: Remove an alias
2567
2568
2569 %upgrade: Upgrade your IPython installation
2570
2571 This will copy the config files that don't yet exist in your ipython dir
2572 from the system config dir. Use this after upgrading IPython if you
2573 don't wish to delete your .ipython dir.
2574
2575 Call with -nolegacy to get rid of ipythonrc* files (recommended for new
2576 users)
2577
2578
2579 %who: Print all interactive variables, with some minimal formatting.
2580
2581 If any arguments are given, only variables whose type matches one of
2582 these are printed. For example:
2583
2584 %who function str
2585
2586 will only list functions and strings, excluding all other types of
2587 variables. To find the proper type names, simply use type(var) at a
2588 command line to see how python prints type names. For example:
2589
2590 In [1]: type('hello')
2591 Out[1]: <type 'str'>
2592
2593 indicates that the type name for strings is 'str'.
2594
2595 %who always excludes executed names loaded through your configuration
2596 file and things which are internal to IPython.
2597
2598 This is deliberate, as typically you may load many modules and the
2599 purpose of %who is to show you only what you've manually defined.
2600
2601
2602 %who_ls: Return a sorted list of all interactive variables.
2603
2604 If arguments are given, only variables of types matching these arguments
2605 are returned.
2606
2607
2608 %whos: Like %who, but gives some extra information about each variable.
2609
2610 The same type filtering of %who can be applied here.
2611
2612 For all variables, the type is printed. Additionally it prints:
2613
2614 - For ,[],(): their length.
2615
2616 - For numpy and Numeric arrays, a summary with shape, number of
2617 elements, typecode and size in memory.
2618
2619 - Everything else: a string representation, snipping their middle if too
2620 long.
2621
2622
2623 %xmode: Switch modes for the exception handlers.
2624
2625 Valid modes: Plain, Context and Verbose.
2626
2627 If called without arguments, acts as a toggle.
2628
2138
2139 Print information about the magic function system.
2140
2141 **%mglob**::
2142
2143 This program allows specifying filenames with "mglob" mechanism.
2144 Supported syntax in globs (wilcard matching patterns)::
2145
2146 *.cpp ?ellowo*
2147 - obvious. Differs from normal glob in that dirs are not included.
2148 Unix users might want to write this as: "*.cpp" "?ellowo*"
2149 rec:/usr/share=*.txt,*.doc
2150 - get all *.txt and *.doc under /usr/share,
2151 recursively
2152 rec:/usr/share
2153 - All files under /usr/share, recursively
2154 rec:*.py
2155 - All .py files under current working dir, recursively
2156 foo
2157 - File or dir foo
2158 !*.bak readme*
2159 - readme*, exclude files ending with .bak
2160 !.svn/ !.hg/ !*_Data/ rec:.
2161 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
2162 Trailing / is the key, \ does not work!
2163 dir:foo
2164 - the directory foo if it exists (not files in foo)
2165 dir:*
2166 - all directories in current folder
2167 foo.py bar.* !h* rec:*.py
2168 - Obvious. !h* exclusion only applies for rec:*.py.
2169 foo.py is *not* included twice.
2170 @filelist.txt
2171 - All files listed in 'filelist.txt' file, on separate lines.
2172
2173 **%page**::
2174
2175 Pretty print the object and display it through a pager.
2176
2177 %page [options] OBJECT
2178
2179 If no object is given, use _ (last output).
2180
2181 Options:
2182
2183 -r: page str(object), don't pretty-print it.
2184
2185 **%pdb**::
2186
2187 Control the automatic calling of the pdb interactive debugger.
2188
2189 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
2190 argument it works as a toggle.
2191
2192 When an exception is triggered, IPython can optionally call the
2193 interactive pdb debugger after the traceback printout. %pdb toggles
2194 this feature on and off.
2195
2196 The initial state of this feature is set in your ipythonrc
2197 configuration file (the variable is called 'pdb').
2198
2199 If you want to just activate the debugger AFTER an exception has fired,
2200 without having to type '%pdb on' and rerunning your code, you can use
2201 the %debug magic.
2202
2203 **%pdef**::
2204
2205 Print the definition header for any callable object.
2206
2207 If the object is a class, print the constructor information.
2208
2209 **%pdoc**::
2210
2211 Print the docstring for an object.
2212
2213 If the given object is a class, it will print both the class and the
2214 constructor docstrings.
2215
2216 **%pfile**::
2217
2218 Print (or run through pager) the file where an object is defined.
2219
2220 The file opens at the line where the object definition begins. IPython
2221 will honor the environment variable PAGER if set, and otherwise will
2222 do its best to print the file in a convenient form.
2223
2224 If the given argument is not an object currently defined, IPython will
2225 try to interpret it as a filename (automatically adding a .py extension
2226 if needed). You can thus use %pfile as a syntax highlighting code
2227 viewer.
2228
2229 **%pinfo**::
2230
2231 Provide detailed information about an object.
2232
2233 '%pinfo object' is just a synonym for object? or ?object.
2234
2235 **%popd**::
2236
2237 Change to directory popped off the top of the stack.
2238
2239 **%profile**::
2240
2241 Print your currently active IPyhton profile.
2242
2243 **%prun**::
2244
2245 Run a statement through the python code profiler.
2246
2247 Usage:\
2248 %prun [options] statement
2249
2250 The given statement (which doesn't require quote marks) is run via the
2251 python profiler in a manner similar to the profile.run() function.
2252 Namespaces are internally managed to work correctly; profile.run
2253 cannot be used in IPython because it makes certain assumptions about
2254 namespaces which do not hold under IPython.
2255
2256 Options:
2257
2258 -l <limit>: you can place restrictions on what or how much of the
2259 profile gets printed. The limit value can be:
2260
2261 * A string: only information for function names containing this string
2262 is printed.
2263
2264 * An integer: only these many lines are printed.
2265
2266 * A float (between 0 and 1): this fraction of the report is printed
2267 (for example, use a limit of 0.4 to see the topmost 40% only).
2268
2269 You can combine several limits with repeated use of the option. For
2270 example, '-l __init__ -l 5' will print only the topmost 5 lines of
2271 information about class constructors.
2272
2273 -r: return the pstats.Stats object generated by the profiling. This
2274 object has all the information about the profile in it, and you can
2275 later use it for further analysis or in other functions.
2276
2277 -s <key>: sort profile by given key. You can provide more than one key
2278 by using the option several times: '-s key1 -s key2 -s key3...'. The
2279 default sorting key is 'time'.
2280
2281 The following is copied verbatim from the profile documentation
2282 referenced below:
2283
2284 When more than one key is provided, additional keys are used as
2285 secondary criteria when the there is equality in all keys selected
2286 before them.
2287
2288 Abbreviations can be used for any key names, as long as the
2289 abbreviation is unambiguous. The following are the keys currently
2290 defined:
2291
2292 Valid Arg Meaning\
2293 "calls" call count\
2294 "cumulative" cumulative time\
2295 "file" file name\
2296 "module" file name\
2297 "pcalls" primitive call count\
2298 "line" line number\
2299 "name" function name\
2300 "nfl" name/file/line\
2301 "stdname" standard name\
2302 "time" internal time
2303
2304 Note that all sorts on statistics are in descending order (placing
2305 most time consuming items first), where as name, file, and line number
2306 searches are in ascending order (i.e., alphabetical). The subtle
2307 distinction between "nfl" and "stdname" is that the standard name is a
2308 sort of the name as printed, which means that the embedded line
2309 numbers get compared in an odd way. For example, lines 3, 20, and 40
2310 would (if the file names were the same) appear in the string order
2311 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
2312 line numbers. In fact, sort_stats("nfl") is the same as
2313 sort_stats("name", "file", "line").
2314
2315 -T <filename>: save profile results as shown on screen to a text
2316 file. The profile is still shown on screen.
2317
2318 -D <filename>: save (via dump_stats) profile statistics to given
2319 filename. This data is in a format understod by the pstats module, and
2320 is generated by a call to the dump_stats() method of profile
2321 objects. The profile is still shown on screen.
2322
2323 If you want to run complete programs under the profiler's control, use
2324 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
2325 contains profiler specific options as described here.
2326
2327 You can read the complete documentation for the profile module with:\
2328 In [1]: import profile; profile.help()
2329
2330 **%psearch**::
2331
2332 Search for object in namespaces by wildcard.
2333
2334 %psearch [options] PATTERN [OBJECT TYPE]
2335
2336 Note: ? can be used as a synonym for %psearch, at the beginning or at
2337 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
2338 rest of the command line must be unchanged (options come first), so
2339 for example the following forms are equivalent
2340
2341 %psearch -i a* function
2342 -i a* function?
2343 ?-i a* function
2344
2345 Arguments:
2346
2347 PATTERN
2348
2349 where PATTERN is a string containing * as a wildcard similar to its
2350 use in a shell. The pattern is matched in all namespaces on the
2351 search path. By default objects starting with a single _ are not
2352 matched, many IPython generated objects have a single
2353 underscore. The default is case insensitive matching. Matching is
2354 also done on the attributes of objects and not only on the objects
2355 in a module.
2356
2357 [OBJECT TYPE]
2358
2359 Is the name of a python type from the types module. The name is
2360 given in lowercase without the ending type, ex. StringType is
2361 written string. By adding a type here only objects matching the
2362 given type are matched. Using all here makes the pattern match all
2363 types (this is the default).
2364
2365 Options:
2366
2367 -a: makes the pattern match even objects whose names start with a
2368 single underscore. These names are normally ommitted from the
2369 search.
2370
2371 -i/-c: make the pattern case insensitive/sensitive. If neither of
2372 these options is given, the default is read from your ipythonrc
2373 file. The option name which sets this value is
2374 'wildcards_case_sensitive'. If this option is not specified in your
2375 ipythonrc file, IPython's internal default is to do a case sensitive
2376 search.
2377
2378 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
2379 specifiy can be searched in any of the following namespaces:
2380 'builtin', 'user', 'user_global','internal', 'alias', where
2381 'builtin' and 'user' are the search defaults. Note that you should
2382 not use quotes when specifying namespaces.
2383
2384 'Builtin' contains the python module builtin, 'user' contains all
2385 user data, 'alias' only contain the shell aliases and no python
2386 objects, 'internal' contains objects used by IPython. The
2387 'user_global' namespace is only used by embedded IPython instances,
2388 and it contains module-level globals. You can add namespaces to the
2389 search with -s or exclude them with -e (these options can be given
2390 more than once).
2391
2392 Examples:
2393
2394 %psearch a* -> objects beginning with an a
2395 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
2396 %psearch a* function -> all functions beginning with an a
2397 %psearch re.e* -> objects beginning with an e in module re
2398 %psearch r*.e* -> objects that start with e in modules starting in r
2399 %psearch r*.* string -> all strings in modules beginning with r
2400
2401 Case sensitve search:
2402
2403 %psearch -c a* list all object beginning with lower case a
2404
2405 Show objects beginning with a single _:
2406
2407 %psearch -a _* list objects beginning with a single underscore
2408
2409 **%psource**::
2410
2411 Print (or run through pager) the source code for an object.
2412
2413 **%pushd**::
2414
2415 Place the current dir on stack and change directory.
2416
2417 Usage:\
2418 %pushd ['dirname']
2419
2420 **%pwd**::
2421
2422 Return the current working directory path.
2423
2424 **%pycat**::
2425
2426 Show a syntax-highlighted file through a pager.
2427
2428 This magic is similar to the cat utility, but it will assume the file
2429 to be Python source and will show it with syntax highlighting.
2430
2431 **%quickref**::
2432
2433 Show a quick reference sheet
2434
2435 **%quit**::
2436
2437 Exit IPython, confirming if configured to do so (like %exit)
2438
2439 **%r**::
2440
2441 Repeat previous input.
2442
2443 Note: Consider using the more powerfull %rep instead!
2444
2445 If given an argument, repeats the previous command which starts with
2446 the same string, otherwise it just repeats the previous input.
2447
2448 Shell escaped commands (with ! as first character) are not recognized
2449 by this system, only pure python code and magic commands.
2450
2451 **%rehashdir**::
2452
2453 Add executables in all specified dirs to alias table
2454
2455 Usage:
2456
2457 %rehashdir c:/bin;c:/tools
2458 - Add all executables under c:/bin and c:/tools to alias table, in
2459 order to make them directly executable from any directory.
2460
2461 Without arguments, add all executables in current directory.
2462
2463 **%rehashx**::
2464
2465 Update the alias table with all executable files in $PATH.
2466
2467 This version explicitly checks that every entry in $PATH is a file
2468 with execute access (os.X_OK), so it is much slower than %rehash.
2469
2470 Under Windows, it checks executability as a match agains a
2471 '|'-separated string of extensions, stored in the IPython config
2472 variable win_exec_ext. This defaults to 'exe|com|bat'.
2473
2474 This function also resets the root module cache of module completer,
2475 used on slow filesystems.
2476
2477 **%rep**::
2478
2479 Repeat a command, or get command to input line for editing
2480
2481 - %rep (no arguments):
2482
2483 Place a string version of last computation result (stored in the special '_'
2484 variable) to the next input prompt. Allows you to create elaborate command
2485 lines without using copy-paste::
2486
2487 $ l = ["hei", "vaan"]
2488 $ "".join(l)
2489 ==> heivaan
2490 $ %rep
2491 $ heivaan_ <== cursor blinking
2492
2493 %rep 45
2494
2495 Place history line 45 to next input prompt. Use %hist to find out the
2496 number.
2497
2498 %rep 1-4 6-7 3
2499
2500 Repeat the specified lines immediately. Input slice syntax is the same as
2501 in %macro and %save.
2502
2503 %rep foo
2504
2505 Place the most recent line that has the substring "foo" to next input.
2506 (e.g. 'svn ci -m foobar').
2507
2508 **%reset**::
2509
2510 Resets the namespace by removing all names defined by the user.
2511
2512 Input/Output history are left around in case you need them.
2513
2514 **%run**::
2515
2516 Run the named file inside IPython as a program.
2517
2518 Usage:\
2519 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2520
2521 Parameters after the filename are passed as command-line arguments to
2522 the program (put in sys.argv). Then, control returns to IPython's
2523 prompt.
2524
2525 This is similar to running at a system prompt:\
2526 $ python file args\
2527 but with the advantage of giving you IPython's tracebacks, and of
2528 loading all variables into your interactive namespace for further use
2529 (unless -p is used, see below).
2530
2531 The file is executed in a namespace initially consisting only of
2532 __name__=='__main__' and sys.argv constructed as indicated. It thus
2533 sees its environment as if it were being run as a stand-alone program
2534 (except for sharing global objects such as previously imported
2535 modules). But after execution, the IPython interactive namespace gets
2536 updated with all variables defined in the program (except for __name__
2537 and sys.argv). This allows for very convenient loading of code for
2538 interactive work, while giving each program a 'clean sheet' to run in.
2539
2540 Options:
2541
2542 -n: __name__ is NOT set to '__main__', but to the running file's name
2543 without extension (as python does under import). This allows running
2544 scripts and reloading the definitions in them without calling code
2545 protected by an ' if __name__ == "__main__" ' clause.
2546
2547 -i: run the file in IPython's namespace instead of an empty one. This
2548 is useful if you are experimenting with code written in a text editor
2549 which depends on variables defined interactively.
2550
2551 -e: ignore sys.exit() calls or SystemExit exceptions in the script
2552 being run. This is particularly useful if IPython is being used to
2553 run unittests, which always exit with a sys.exit() call. In such
2554 cases you are interested in the output of the test results, not in
2555 seeing a traceback of the unittest module.
2556
2557 -t: print timing information at the end of the run. IPython will give
2558 you an estimated CPU time consumption for your script, which under
2559 Unix uses the resource module to avoid the wraparound problems of
2560 time.clock(). Under Unix, an estimate of time spent on system tasks
2561 is also given (for Windows platforms this is reported as 0.0).
2562
2563 If -t is given, an additional -N<N> option can be given, where <N>
2564 must be an integer indicating how many times you want the script to
2565 run. The final timing report will include total and per run results.
2566
2567 For example (testing the script uniq_stable.py):
2568
2569 In [1]: run -t uniq_stable
2570
2571 IPython CPU timings (estimated):\
2572 User : 0.19597 s.\
2573 System: 0.0 s.\
2574
2575 In [2]: run -t -N5 uniq_stable
2576
2577 IPython CPU timings (estimated):\
2578 Total runs performed: 5\
2579 Times : Total Per run\
2580 User : 0.910862 s, 0.1821724 s.\
2581 System: 0.0 s, 0.0 s.
2582
2583 -d: run your program under the control of pdb, the Python debugger.
2584 This allows you to execute your program step by step, watch variables,
2585 etc. Internally, what IPython does is similar to calling:
2586
2587 pdb.run('execfile("YOURFILENAME")')
2588
2589 with a breakpoint set on line 1 of your file. You can change the line
2590 number for this automatic breakpoint to be <N> by using the -bN option
2591 (where N must be an integer). For example:
2592
2593 %run -d -b40 myscript
2594
2595 will set the first breakpoint at line 40 in myscript.py. Note that
2596 the first breakpoint must be set on a line which actually does
2597 something (not a comment or docstring) for it to stop execution.
2598
2599 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2600 first enter 'c' (without qoutes) to start execution up to the first
2601 breakpoint.
2602
2603 Entering 'help' gives information about the use of the debugger. You
2604 can easily see pdb's full documentation with "import pdb;pdb.help()"
2605 at a prompt.
2606
2607 -p: run program under the control of the Python profiler module (which
2608 prints a detailed report of execution times, function calls, etc).
2609
2610 You can pass other options after -p which affect the behavior of the
2611 profiler itself. See the docs for %prun for details.
2612
2613 In this mode, the program's variables do NOT propagate back to the
2614 IPython interactive namespace (because they remain in the namespace
2615 where the profiler executes them).
2616
2617 Internally this triggers a call to %prun, see its documentation for
2618 details on the options available specifically for profiling.
2619
2620 There is one special usage for which the text above doesn't apply:
2621 if the filename ends with .ipy, the file is run as ipython script,
2622 just as if the commands were written on IPython prompt.
2623
2624 **%runlog**::
2625
2626 Run files as logs.
2627
2628 Usage:\
2629 %runlog file1 file2 ...
2630
2631 Run the named files (treating them as log files) in sequence inside
2632 the interpreter, and return to the prompt. This is much slower than
2633 %run because each line is executed in a try/except block, but it
2634 allows running files with syntax errors in them.
2635
2636 Normally IPython will guess when a file is one of its own logfiles, so
2637 you can typically use %run even for logs. This shorthand allows you to
2638 force any file to be treated as a log file.
2639
2640 **%save**::
2641
2642 Save a set of lines to a given filename.
2643
2644 Usage:\
2645 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2646
2647 Options:
2648
2649 -r: use 'raw' input. By default, the 'processed' history is used,
2650 so that magics are loaded in their transformed version to valid
2651 Python. If this option is given, the raw input as typed as the
2652 command line is used instead.
2653
2654 This function uses the same syntax as %macro for line extraction, but
2655 instead of creating a macro it saves the resulting string to the
2656 filename you specify.
2657
2658 It adds a '.py' extension to the file if you don't do so yourself, and
2659 it asks for confirmation before overwriting existing files.
2660
2661 **%sc**::
2662
2663 Shell capture - execute a shell command and capture its output.
2664
2665 DEPRECATED. Suboptimal, retained for backwards compatibility.
2666
2667 You should use the form 'var = !command' instead. Example:
2668
2669 "%sc -l myfiles = ls ~" should now be written as
2670
2671 "myfiles = !ls ~"
2672
2673 myfiles.s, myfiles.l and myfiles.n still apply as documented
2674 below.
2675
2676 --
2677 %sc [options] varname=command
2678
2679 IPython will run the given command using commands.getoutput(), and
2680 will then update the user's interactive namespace with a variable
2681 called varname, containing the value of the call. Your command can
2682 contain shell wildcards, pipes, etc.
2683
2684 The '=' sign in the syntax is mandatory, and the variable name you
2685 supply must follow Python's standard conventions for valid names.
2686
2687 (A special format without variable name exists for internal use)
2688
2689 Options:
2690
2691 -l: list output. Split the output on newlines into a list before
2692 assigning it to the given variable. By default the output is stored
2693 as a single string.
2694
2695 -v: verbose. Print the contents of the variable.
2696
2697 In most cases you should not need to split as a list, because the
2698 returned value is a special type of string which can automatically
2699 provide its contents either as a list (split on newlines) or as a
2700 space-separated string. These are convenient, respectively, either
2701 for sequential processing or to be passed to a shell command.
2702
2703 For example:
2704
2705 # Capture into variable a
2706 In [9]: sc a=ls *py
2707
2708 # a is a string with embedded newlines
2709 In [10]: a
2710 Out[10]: 'setup.py win32_manual_post_install.py'
2711
2712 # which can be seen as a list:
2713 In [11]: a.l
2714 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2715
2716 # or as a whitespace-separated string:
2717 In [12]: a.s
2718 Out[12]: 'setup.py win32_manual_post_install.py'
2719
2720 # a.s is useful to pass as a single command line:
2721 In [13]: !wc -l $a.s
2722 146 setup.py
2723 130 win32_manual_post_install.py
2724 276 total
2725
2726 # while the list form is useful to loop over:
2727 In [14]: for f in a.l:
2728 ....: !wc -l $f
2729 ....:
2730 146 setup.py
2731 130 win32_manual_post_install.py
2732
2733 Similiarly, the lists returned by the -l option are also special, in
2734 the sense that you can equally invoke the .s attribute on them to
2735 automatically get a whitespace-separated string from their contents:
2736
2737 In [1]: sc -l b=ls *py
2738
2739 In [2]: b
2740 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2741
2742 In [3]: b.s
2743 Out[3]: 'setup.py win32_manual_post_install.py'
2744
2745 In summary, both the lists and strings used for ouptut capture have
2746 the following special attributes:
2747
2748 .l (or .list) : value as list.
2749 .n (or .nlstr): value as newline-separated string.
2750 .s (or .spstr): value as space-separated string.
2751
2752 **%store**::
2753
2754 Lightweight persistence for python variables.
2755
2756 Example:
2757
2758 ville@badger[~]|1> A = ['hello',10,'world']\
2759 ville@badger[~]|2> %store A\
2760 ville@badger[~]|3> Exit
2761
2762 (IPython session is closed and started again...)
2763
2764 ville@badger:~$ ipython -p pysh\
2765 ville@badger[~]|1> print A
2766
2767 ['hello', 10, 'world']
2768
2769 Usage:
2770
2771 %store - Show list of all variables and their current values\
2772 %store <var> - Store the *current* value of the variable to disk\
2773 %store -d <var> - Remove the variable and its value from storage\
2774 %store -z - Remove all variables from storage\
2775 %store -r - Refresh all variables from store (delete current vals)\
2776 %store foo >a.txt - Store value of foo to new file a.txt\
2777 %store foo >>a.txt - Append value of foo to file a.txt\
2778
2779 It should be noted that if you change the value of a variable, you
2780 need to %store it again if you want to persist the new value.
2781
2782 Note also that the variables will need to be pickleable; most basic
2783 python types can be safely %stored.
2784
2785 Also aliases can be %store'd across sessions.
2786
2787 **%sx**::
2788
2789 Shell execute - run a shell command and capture its output.
2790
2791 %sx command
2792
2793 IPython will run the given command using commands.getoutput(), and
2794 return the result formatted as a list (split on '\n'). Since the
2795 output is _returned_, it will be stored in ipython's regular output
2796 cache Out[N] and in the '_N' automatic variables.
2797
2798 Notes:
2799
2800 1) If an input line begins with '!!', then %sx is automatically
2801 invoked. That is, while:
2802 !ls
2803 causes ipython to simply issue system('ls'), typing
2804 !!ls
2805 is a shorthand equivalent to:
2806 %sx ls
2807
2808 2) %sx differs from %sc in that %sx automatically splits into a list,
2809 like '%sc -l'. The reason for this is to make it as easy as possible
2810 to process line-oriented shell output via further python commands.
2811 %sc is meant to provide much finer control, but requires more
2812 typing.
2813
2814 3) Just like %sc -l, this is a list with special attributes:
2815
2816 .l (or .list) : value as list.
2817 .n (or .nlstr): value as newline-separated string.
2818 .s (or .spstr): value as whitespace-separated string.
2819
2820 This is very useful when trying to use such lists as arguments to
2821 system commands.
2822
2823 **%system_verbose**::
2824
2825 Set verbose printing of system calls.
2826
2827 If called without an argument, act as a toggle
2828
2829 **%time**::
2830
2831 Time execution of a Python statement or expression.
2832
2833 The CPU and wall clock times are printed, and the value of the
2834 expression (if any) is returned. Note that under Win32, system time
2835 is always reported as 0, since it can not be measured.
2836
2837 This function provides very basic timing functionality. In Python
2838 2.3, the timeit module offers more control and sophistication, so this
2839 could be rewritten to use it (patches welcome).
2840
2841 Some examples:
2842
2843 In [1]: time 2**128
2844 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2845 Wall time: 0.00
2846 Out[1]: 340282366920938463463374607431768211456L
2847
2848 In [2]: n = 1000000
2849
2850 In [3]: time sum(range(n))
2851 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2852 Wall time: 1.37
2853 Out[3]: 499999500000L
2854
2855 In [4]: time print 'hello world'
2856 hello world
2857 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2858 Wall time: 0.00
2859
2860 Note that the time needed by Python to compile the given expression
2861 will be reported if it is more than 0.1s. In this example, the
2862 actual exponentiation is done by Python at compilation time, so while
2863 the expression can take a noticeable amount of time to compute, that
2864 time is purely due to the compilation:
2865
2866 In [5]: time 3**9999;
2867 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2868 Wall time: 0.00 s
2869
2870 In [6]: time 3**999999;
2871 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2872 Wall time: 0.00 s
2873 Compiler : 0.78 s
2874
2875 **%timeit**::
2876
2877 Time execution of a Python statement or expression
2878
2879 Usage:\
2880 %timeit [-n<N> -r<R> [-t|-c]] statement
2881
2882 Time execution of a Python statement or expression using the timeit
2883 module.
2884
2885 Options:
2886 -n<N>: execute the given statement <N> times in a loop. If this value
2887 is not given, a fitting value is chosen.
2888
2889 -r<R>: repeat the loop iteration <R> times and take the best result.
2890 Default: 3
2891
2892 -t: use time.time to measure the time, which is the default on Unix.
2893 This function measures wall time.
2894
2895 -c: use time.clock to measure the time, which is the default on
2896 Windows and measures wall time. On Unix, resource.getrusage is used
2897 instead and returns the CPU user time.
2898
2899 -p<P>: use a precision of <P> digits to display the timing result.
2900 Default: 3
2901
2902
2903 Examples:\
2904 In [1]: %timeit pass
2905 10000000 loops, best of 3: 53.3 ns per loop
2906
2907 In [2]: u = None
2908
2909 In [3]: %timeit u is None
2910 10000000 loops, best of 3: 184 ns per loop
2911
2912 In [4]: %timeit -r 4 u == None
2913 1000000 loops, best of 4: 242 ns per loop
2914
2915 In [5]: import time
2916
2917 In [6]: %timeit -n1 time.sleep(2)
2918 1 loops, best of 3: 2 s per loop
2919
2920
2921 The times reported by %timeit will be slightly higher than those
2922 reported by the timeit.py script when variables are accessed. This is
2923 due to the fact that %timeit executes the statement in the namespace
2924 of the shell, compared with timeit.py, which uses a single setup
2925 statement to import function or create variables. Generally, the bias
2926 does not matter as long as results from timeit.py are not mixed with
2927 those from %timeit.
2928
2929 **%unalias**::
2930
2931 Remove an alias
2932
2933 **%upgrade**::
2934
2935 Upgrade your IPython installation
2936
2937 This will copy the config files that don't yet exist in your
2938 ipython dir from the system config dir. Use this after upgrading
2939 IPython if you don't wish to delete your .ipython dir.
2940
2941 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2942 new users)
2943
2944 **%which**::
2945
2946 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
2947
2948 Traverses PATH and prints all files (not just executables!) that match the
2949 pattern on command line. Probably more useful in finding stuff
2950 interactively than 'which', which only prints the first matching item.
2951
2952 Also discovers and expands aliases, so you'll see what will be executed
2953 when you call an alias.
2954
2955 Example:
2956
2957 [~]|62> %which d
2958 d -> ls -F --color=auto
2959 == c:\cygwin\bin\ls.exe
2960 c:\cygwin\bin\d.exe
2961
2962 [~]|64> %which diff*
2963 diff3 -> diff3
2964 == c:\cygwin\bin\diff3.exe
2965 diff -> diff
2966 == c:\cygwin\bin\diff.exe
2967 c:\cygwin\bin\diff.exe
2968 c:\cygwin\bin\diff3.exe
2969
2970 **%who**::
2971
2972 Print all interactive variables, with some minimal formatting.
2973
2974 If any arguments are given, only variables whose type matches one of
2975 these are printed. For example:
2976
2977 %who function str
2978
2979 will only list functions and strings, excluding all other types of
2980 variables. To find the proper type names, simply use type(var) at a
2981 command line to see how python prints type names. For example:
2982
2983 In [1]: type('hello')\
2984 Out[1]: <type 'str'>
2985
2986 indicates that the type name for strings is 'str'.
2987
2988 %who always excludes executed names loaded through your configuration
2989 file and things which are internal to IPython.
2990
2991 This is deliberate, as typically you may load many modules and the
2992 purpose of %who is to show you only what you've manually defined.
2993
2994 **%who_ls**::
2995
2996 Return a sorted list of all interactive variables.
2997
2998 If arguments are given, only variables of types matching these
2999 arguments are returned.
3000
3001 **%whos**::
3002
3003 Like %who, but gives some extra information about each variable.
3004
3005 The same type filtering of %who can be applied here.
3006
3007 For all variables, the type is printed. Additionally it prints:
3008
3009 - For {},[],(): their length.
3010
3011 - For numpy and Numeric arrays, a summary with shape, number of
3012 elements, typecode and size in memory.
3013
3014 - Everything else: a string representation, snipping their middle if
3015 too long.
3016
3017 **%xmode**::
3018
3019 Switch modes for the exception handlers.
3020
3021 Valid modes: Plain, Context and Verbose.
3022
3023 If called without arguments, acts as a toggle.
3024
3025 .. magic_end
2629
3026
2630 Access to the standard Python help
3027 Access to the standard Python help
2631 ----------------------------------
3028 ----------------------------------
2632
3029
2633 As of Python 2.1, a help system is available with access to object
3030 As of Python 2.1, a help system is available with access to object
2634 docstrings and the Python manuals. Simply type 'help' (no quotes) to
3031 docstrings and the Python manuals. Simply type 'help' (no quotes) to
2635 access it. You can also type help(object) to obtain information about a
3032 access it. You can also type help(object) to obtain information about a
2636 given object, and help('keyword') for information on a keyword. As noted
3033 given object, and help('keyword') for information on a keyword. As noted
2637 in sec. 3.1 <node3.html#sec:help-access>, you need to properly configure
3034 in sec. `accessing help`_, you need to properly configure
2638 your environment variable PYTHONDOCS for this feature to work correctly.
3035 your environment variable PYTHONDOCS for this feature to work correctly.
2639
3036
2640
3037
2641
2642 Dynamic object information
3038 Dynamic object information
2643 --------------------------
3039 --------------------------
2644
3040
2645 Typing ?word or word? prints detailed information about an object. If
3041 Typing ?word or word? prints detailed information about an object. If
2646 certain strings in the object are too long (docstrings, code, etc.) they
3042 certain strings in the object are too long (docstrings, code, etc.) they
2647 get snipped in the center for brevity. This system gives access variable
3043 get snipped in the center for brevity. This system gives access variable
2648 types and values, full source code for any object (if available),
3044 types and values, full source code for any object (if available),
2649 function prototypes and other useful information.
3045 function prototypes and other useful information.
2650
3046
2651 Typing ??word or word?? gives access to the full information without
3047 Typing ??word or word?? gives access to the full information without
2652 snipping long strings. Long strings are sent to the screen through the
3048 snipping long strings. Long strings are sent to the screen through the
2653 less pager if longer than the screen and printed otherwise. On systems
3049 less pager if longer than the screen and printed otherwise. On systems
2654 lacking the less command, IPython uses a very basic internal pager.
3050 lacking the less command, IPython uses a very basic internal pager.
2655
3051
2656 The following magic functions are particularly useful for gathering
3052 The following magic functions are particularly useful for gathering
2657 information about your working environment. You can get more details by
3053 information about your working environment. You can get more details by
2658 typing %magic or querying them individually (use %function_name? with or
3054 typing %magic or querying them individually (use %function_name? with or
2659 without the %), this is just a summary:
3055 without the %), this is just a summary:
2660
3056
2661 * [%pdoc <object>:] Print (or run through a pager if too long) the
3057 * **%pdoc <object>**: Print (or run through a pager if too long) the
2662 docstring for an object. If the given object is a class, it will
3058 docstring for an object. If the given object is a class, it will
2663 print both the class and the constructor docstrings.
3059 print both the class and the constructor docstrings.
2664 * [%pdef <object>:] Print the definition header for any callable
3060 * **%pdef <object>**: Print the definition header for any callable
2665 object. If the object is a class, print the constructor information.
3061 object. If the object is a class, print the constructor information.
2666 * [%psource <object>:] Print (or run through a pager if too long)
3062 * **%psource <object>**: Print (or run through a pager if too long)
2667 the source code for an object.
3063 the source code for an object.
2668 * [%pfile <object>:] Show the entire source file where an object was
3064 * **%pfile <object>**: Show the entire source file where an object was
2669 defined via a pager, opening it at the line where the object
3065 defined via a pager, opening it at the line where the object
2670 definition begins.
3066 definition begins.
2671 * [%who/%whos:] These functions give information about identifiers
3067 * **%who/%whos**: These functions give information about identifiers
2672 you have defined interactively (not things you loaded or defined
3068 you have defined interactively (not things you loaded or defined
2673 in your configuration files). %who just prints a list of
3069 in your configuration files). %who just prints a list of
2674 identifiers and %whos prints a table with some basic details about
3070 identifiers and %whos prints a table with some basic details about
2675 each identifier.
3071 each identifier.
2676
3072
2677 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
3073 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
2678 %pdef, %psource) give you access to documentation even on things which
3074 %pdef, %psource) give you access to documentation even on things which
2679 are not really defined as separate identifiers. Try for example typing
3075 are not really defined as separate identifiers. Try for example typing
2680 {}.get? or after doing import os, type os.path.abspath??.
3076 {}.get? or after doing import os, type os.path.abspath??.
2681
3077
2682
3078
3079 .. _Readline:
2683
3080
2684 Readline-based features
3081 Readline-based features
2685 -----------------------
3082 -----------------------
2686
3083
2687 These features require the GNU readline library, so they won't work if
3084 These features require the GNU readline library, so they won't work if
2688 your Python installation lacks readline support. We will first describe
3085 your Python installation lacks readline support. We will first describe
2689 the default behavior IPython uses, and then how to change it to suit
3086 the default behavior IPython uses, and then how to change it to suit
2690 your preferences.
3087 your preferences.
2691
3088
2692
3089
2693 Command line completion
3090 Command line completion
2694 -----------------------
3091 +++++++++++++++++++++++
2695
3092
2696 At any time, hitting TAB will complete any available python commands or
3093 At any time, hitting TAB will complete any available python commands or
2697 variable names, and show you a list of the possible completions if
3094 variable names, and show you a list of the possible completions if
2698 there's no unambiguous one. It will also complete filenames in the
3095 there's no unambiguous one. It will also complete filenames in the
2699 current directory if no python names match what you've typed so far.
3096 current directory if no python names match what you've typed so far.
2700
3097
2701
3098
2702 Search command history
3099 Search command history
2703 ----------------------
3100 ++++++++++++++++++++++
2704
3101
2705 IPython provides two ways for searching through previous input and thus
3102 IPython provides two ways for searching through previous input and thus
2706 reduce the need for repetitive typing:
3103 reduce the need for repetitive typing:
2707
3104
2708 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
3105 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
2709 (next,down) to search through only the history items that match
3106 (next,down) to search through only the history items that match
2710 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
3107 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
2711 prompt, they just behave like normal arrow keys.
3108 prompt, they just behave like normal arrow keys.
2712 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
3109 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
2713 searches your history for lines that contain what you've typed so
3110 searches your history for lines that contain what you've typed so
2714 far, completing as much as it can.
3111 far, completing as much as it can.
2715
3112
2716
3113
2717 Persistent command history across sessions
3114 Persistent command history across sessions
2718 ------------------------------------------
3115 ++++++++++++++++++++++++++++++++++++++++++
2719
3116
2720 IPython will save your input history when it leaves and reload it next
3117 IPython will save your input history when it leaves and reload it next
2721 time you restart it. By default, the history file is named
3118 time you restart it. By default, the history file is named
2722 $IPYTHONDIR/history, but if you've loaded a named profile,
3119 $IPYTHONDIR/history, but if you've loaded a named profile,
2723 '-PROFILE_NAME' is appended to the name. This allows you to keep
3120 '-PROFILE_NAME' is appended to the name. This allows you to keep
2724 separate histories related to various tasks: commands related to
3121 separate histories related to various tasks: commands related to
2725 numerical work will not be clobbered by a system shell history, for
3122 numerical work will not be clobbered by a system shell history, for
2726 example.
3123 example.
2727
3124
2728
3125
2729 Autoindent
3126 Autoindent
2730 ----------
3127 ++++++++++
2731
3128
2732 IPython can recognize lines ending in ':' and indent the next line,
3129 IPython can recognize lines ending in ':' and indent the next line,
2733 while also un-indenting automatically after 'raise' or 'return'.
3130 while also un-indenting automatically after 'raise' or 'return'.
2734
3131
2735 This feature uses the readline library, so it will honor your ~/.inputrc
3132 This feature uses the readline library, so it will honor your ~/.inputrc
2736 configuration (or whatever file your INPUTRC variable points to). Adding
3133 configuration (or whatever file your INPUTRC variable points to). Adding
2737 the following lines to your .inputrc file can make indenting/unindenting
3134 the following lines to your .inputrc file can make indenting/unindenting
2738 more convenient (M-i indents, M-u unindents)::
3135 more convenient (M-i indents, M-u unindents)::
2739
3136
2740 $if Python
3137 $if Python
2741 "\M-i": " "
3138 "\M-i": " "
2742 "\M-u": "\d\d\d\d"
3139 "\M-u": "\d\d\d\d"
2743 $endif
3140 $endif
2744
3141
2745 Note that there are 4 spaces between the quote marks after "M-i" above.
3142 Note that there are 4 spaces between the quote marks after "M-i" above.
2746
3143
2747 Warning: this feature is ON by default, but it can cause problems with
3144 Warning: this feature is ON by default, but it can cause problems with
2748 the pasting of multi-line indented code (the pasted code gets
3145 the pasting of multi-line indented code (the pasted code gets
2749 re-indented on each line). A magic function %autoindent allows you to
3146 re-indented on each line). A magic function %autoindent allows you to
2750 toggle it on/off at runtime. You can also disable it permanently on in
3147 toggle it on/off at runtime. You can also disable it permanently on in
2751 your ipythonrc file (set autoindent 0).
3148 your ipythonrc file (set autoindent 0).
2752
3149
2753
3150
2754 Customizing readline behavior
3151 Customizing readline behavior
2755 -----------------------------
3152 +++++++++++++++++++++++++++++
2756
3153
2757 All these features are based on the GNU readline library, which has an
3154 All these features are based on the GNU readline library, which has an
2758 extremely customizable interface. Normally, readline is configured via a
3155 extremely customizable interface. Normally, readline is configured via a
2759 file which defines the behavior of the library; the details of the
3156 file which defines the behavior of the library; the details of the
2760 syntax for this can be found in the readline documentation available
3157 syntax for this can be found in the readline documentation available
2761 with your system or on the Internet. IPython doesn't read this file (if
3158 with your system or on the Internet. IPython doesn't read this file (if
2762 it exists) directly, but it does support passing to readline valid
3159 it exists) directly, but it does support passing to readline valid
2763 options via a simple interface. In brief, you can customize readline by
3160 options via a simple interface. In brief, you can customize readline by
2764 setting the following options in your ipythonrc configuration file (note
3161 setting the following options in your ipythonrc configuration file (note
2765 that these options can not be specified at the command line):
3162 that these options can not be specified at the command line):
2766
3163
2767 * [readline_parse_and_bind:] this option can appear as many times as
3164 * **readline_parse_and_bind**: this option can appear as many times as
2768 you want, each time defining a string to be executed via a
3165 you want, each time defining a string to be executed via a
2769 readline.parse_and_bind() command. The syntax for valid commands
3166 readline.parse_and_bind() command. The syntax for valid commands
2770 of this kind can be found by reading the documentation for the GNU
3167 of this kind can be found by reading the documentation for the GNU
2771 readline library, as these commands are of the kind which readline
3168 readline library, as these commands are of the kind which readline
2772 accepts in its configuration file.
3169 accepts in its configuration file.
2773 * [readline_remove_delims:] a string of characters to be removed
3170 * **readline_remove_delims**: a string of characters to be removed
2774 from the default word-delimiters list used by readline, so that
3171 from the default word-delimiters list used by readline, so that
2775 completions may be performed on strings which contain them. Do not
3172 completions may be performed on strings which contain them. Do not
2776 change the default value unless you know what you're doing.
3173 change the default value unless you know what you're doing.
2777 * [readline_omit__names:] when tab-completion is enabled, hitting
3174 * **readline_omit__names**: when tab-completion is enabled, hitting
2778 <tab> after a '.' in a name will complete all attributes of an
3175 <tab> after a '.' in a name will complete all attributes of an
2779 object, including all the special methods whose names include
3176 object, including all the special methods whose names include
2780 double underscores (like __getitem__ or __class__). If you'd
3177 double underscores (like __getitem__ or __class__). If you'd
2781 rather not see these names by default, you can set this option to
3178 rather not see these names by default, you can set this option to
2782 1. Note that even when this option is set, you can still see those
3179 1. Note that even when this option is set, you can still see those
2783 names by explicitly typing a _ after the period and hitting <tab>:
3180 names by explicitly typing a _ after the period and hitting <tab>:
2784 'name._<tab>' will always complete attribute names starting with '_'.
3181 'name._<tab>' will always complete attribute names starting with '_'.
2785 * [ ] This option is off by default so that new users see all
3182
3183 This option is off by default so that new users see all
2786 attributes of any objects they are dealing with.
3184 attributes of any objects they are dealing with.
2787
3185
2788 You will find the default values along with a corresponding detailed
3186 You will find the default values along with a corresponding detailed
2789 explanation in your ipythonrc file.
3187 explanation in your ipythonrc file.
2790
3188
2791
3189
2792 Session logging and restoring
3190 Session logging and restoring
2793 -----------------------------
3191 -----------------------------
2794
3192
2795 You can log all input from a session either by starting IPython with the
3193 You can log all input from a session either by starting IPython with
2796 command line switches -log or -logfile (see sec. 5.2
3194 the command line switches -log or -logfile (see sec. `command line
2797 <node5.html#sec:cmd-line-opts>)or by activating the logging at any
3195 options`_) or by activating the logging at any moment with the magic
2798 moment with the magic function %logstart.
3196 function %logstart.
2799
3197
2800 Log files can later be reloaded with the -logplay option and IPython
3198 Log files can later be reloaded with the -logplay option and IPython
2801 will attempt to 'replay' the log by executing all the lines in it, thus
3199 will attempt to 'replay' the log by executing all the lines in it, thus
2802 restoring the state of a previous session. This feature is not quite
3200 restoring the state of a previous session. This feature is not quite
2803 perfect, but can still be useful in many cases.
3201 perfect, but can still be useful in many cases.
2804
3202
2805 The log files can also be used as a way to have a permanent record of
3203 The log files can also be used as a way to have a permanent record of
2806 any code you wrote while experimenting. Log files are regular text files
3204 any code you wrote while experimenting. Log files are regular text files
2807 which you can later open in your favorite text editor to extract code or
3205 which you can later open in your favorite text editor to extract code or
2808 to 'clean them up' before using them to replay a session.
3206 to 'clean them up' before using them to replay a session.
2809
3207
2810 The %logstart function for activating logging in mid-session is used as
3208 The %logstart function for activating logging in mid-session is used as
2811 follows:
3209 follows:
2812
3210
2813 %logstart [log_name [log_mode]]
3211 %logstart [log_name [log_mode]]
2814
3212
2815 If no name is given, it defaults to a file named 'log' in your
3213 If no name is given, it defaults to a file named 'log' in your
2816 IPYTHONDIR directory, in 'rotate' mode (see below).
3214 IPYTHONDIR directory, in 'rotate' mode (see below).
2817
3215
2818 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
3216 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
2819 history up to that point and then continues logging.
3217 history up to that point and then continues logging.
2820
3218
2821 %logstart takes a second optional parameter: logging mode. This can be
3219 %logstart takes a second optional parameter: logging mode. This can be
2822 one of (note that the modes are given unquoted):
3220 one of (note that the modes are given unquoted):
2823
3221
2824 * [over:] overwrite existing log_name.
3222 * [over:] overwrite existing log_name.
2825 * [backup:] rename (if exists) to log_name~ and start log_name.
3223 * [backup:] rename (if exists) to log_name~ and start log_name.
2826 * [append:] well, that says it.
3224 * [append:] well, that says it.
2827 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
3225 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
2828
3226
2829 The %logoff and %logon functions allow you to temporarily stop and
3227 The %logoff and %logon functions allow you to temporarily stop and
2830 resume logging to a file which had previously been started with
3228 resume logging to a file which had previously been started with
2831 %logstart. They will fail (with an explanation) if you try to use them
3229 %logstart. They will fail (with an explanation) if you try to use them
2832 before logging has been started.
3230 before logging has been started.
2833
3231
2834
2835
2836 System shell access
3232 System shell access
2837 -------------------
3233 -------------------
2838
3234
2839 Any input line beginning with a ! character is passed verbatim (minus
3235 Any input line beginning with a ! character is passed verbatim (minus
2840 the !, of course) to the underlying operating system. For example,
3236 the !, of course) to the underlying operating system. For example,
2841 typing !ls will run 'ls' in the current directory.
3237 typing !ls will run 'ls' in the current directory.
2842
3238
2843 Manual capture of command output
3239 Manual capture of command output
2844 --------------------------------
3240 --------------------------------
2845
3241
2846 If the input line begins with two exclamation marks, !!, the command is
3242 If the input line begins with two exclamation marks, !!, the command is
2847 executed but its output is captured and returned as a python list, split
3243 executed but its output is captured and returned as a python list, split
2848 on newlines. Any output sent by the subprocess to standard error is
3244 on newlines. Any output sent by the subprocess to standard error is
2849 printed separately, so that the resulting list only captures standard
3245 printed separately, so that the resulting list only captures standard
2850 output. The !! syntax is a shorthand for the %sx magic command.
3246 output. The !! syntax is a shorthand for the %sx magic command.
2851
3247
2852 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
3248 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2853 but allowing more fine-grained control of the capture details, and
3249 but allowing more fine-grained control of the capture details, and
2854 storing the result directly into a named variable. The direct use of
3250 storing the result directly into a named variable. The direct use of
2855 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
3251 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
2856 instead.
3252 instead.
2857
3253
2858 IPython also allows you to expand the value of python variables when
3254 IPython also allows you to expand the value of python variables when
2859 making system calls. Any python variable or expression which you prepend
3255 making system calls. Any python variable or expression which you prepend
2860 with $ will get expanded before the system call is made::
3256 with $ will get expanded before the system call is made::
2861
3257
2862 In [1]: pyvar='Hello world'
3258 In [1]: pyvar='Hello world'
2863 In [2]: !echo "A python variable: $pyvar"
3259 In [2]: !echo "A python variable: $pyvar"
2864 A python variable: Hello world
3260 A python variable: Hello world
2865
3261
2866 If you want the shell to actually see a literal $, you need to type it
3262 If you want the shell to actually see a literal $, you need to type it
2867 twice::
3263 twice::
2868
3264
2869 In [3]: !echo "A system variable: $$HOME"
3265 In [3]: !echo "A system variable: $$HOME"
2870 A system variable: /home/fperez
3266 A system variable: /home/fperez
2871
3267
2872 You can pass arbitrary expressions, though you'll need to delimit them
3268 You can pass arbitrary expressions, though you'll need to delimit them
2873 with {} if there is ambiguity as to the extent of the expression::
3269 with {} if there is ambiguity as to the extent of the expression::
2874
3270
2875 In [5]: x=10
3271 In [5]: x=10
2876 In [6]: y=20
3272 In [6]: y=20
2877 In [13]: !echo $x+y
3273 In [13]: !echo $x+y
2878 10+y
3274 10+y
2879 In [7]: !echo ${x+y}
3275 In [7]: !echo ${x+y}
2880 30
3276 30
2881
3277
2882 Even object attributes can be expanded::
3278 Even object attributes can be expanded::
2883
3279
2884 In [12]: !echo $sys.argv
3280 In [12]: !echo $sys.argv
2885 [/home/fperez/usr/bin/ipython]
3281 [/home/fperez/usr/bin/ipython]
2886
3282
2887
3283
2888 System command aliases
3284 System command aliases
2889 ----------------------
3285 ----------------------
2890
3286
2891 The %alias magic function and the alias option in the ipythonrc
3287 The %alias magic function and the alias option in the ipythonrc
2892 configuration file allow you to define magic functions which are in fact
3288 configuration file allow you to define magic functions which are in fact
2893 system shell commands. These aliases can have parameters.
3289 system shell commands. These aliases can have parameters.
2894
3290
2895 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
3291 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2896
3292
2897 Then, typing '%alias_name params' will execute the system command 'cmd
3293 Then, typing '%alias_name params' will execute the system command 'cmd
2898 params' (from your underlying operating system).
3294 params' (from your underlying operating system).
2899
3295
2900 You can also define aliases with parameters using %s specifiers (one per
3296 You can also define aliases with parameters using %s specifiers (one per
2901 parameter). The following example defines the %parts function as an
3297 parameter). The following example defines the %parts function as an
2902 alias to the command 'echo first %s second %s' where each %s will be
3298 alias to the command 'echo first %s second %s' where each %s will be
2903 replaced by a positional parameter to the call to %parts::
3299 replaced by a positional parameter to the call to %parts::
2904
3300
2905 In [1]: alias parts echo first %s second %s
3301 In [1]: alias parts echo first %s second %s
2906 In [2]: %parts A B
3302 In [2]: %parts A B
2907 first A second B
3303 first A second B
2908 In [3]: %parts A
3304 In [3]: %parts A
2909 Incorrect number of arguments: 2 expected.
3305 Incorrect number of arguments: 2 expected.
2910 parts is an alias to: 'echo first %s second %s'
3306 parts is an alias to: 'echo first %s second %s'
2911
3307
2912 If called with no parameters, %alias prints the table of currently
3308 If called with no parameters, %alias prints the table of currently
2913 defined aliases.
3309 defined aliases.
2914
3310
2915 The %rehash/rehashx magics allow you to load your entire $PATH as
3311 The %rehash/rehashx magics allow you to load your entire $PATH as
2916 ipython aliases. See their respective docstrings (or sec. 6.2
3312 ipython aliases. See their respective docstrings (or sec. 6.2
2917 <#sec:magic> for further details).
3313 <#sec:magic> for further details).
2918
3314
2919
3315
3316 .. _dreload:
2920
3317
2921 Recursive reload
3318 Recursive reload
2922 ----------------
3319 ----------------
2923
3320
2924 The dreload function does a recursive reload of a module: changes made
3321 The dreload function does a recursive reload of a module: changes made
2925 to the module since you imported will actually be available without
3322 to the module since you imported will actually be available without
2926 having to exit.
3323 having to exit.
2927
3324
2928
3325
2929 Verbose and colored exception traceback printouts
3326 Verbose and colored exception traceback printouts
2930 -------------------------------------------------
3327 -------------------------------------------------
2931
3328
2932 IPython provides the option to see very detailed exception tracebacks,
3329 IPython provides the option to see very detailed exception tracebacks,
2933 which can be especially useful when debugging large programs. You can
3330 which can be especially useful when debugging large programs. You can
2934 run any Python file with the %run function to benefit from these
3331 run any Python file with the %run function to benefit from these
2935 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
3332 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
2936 be colored (if your terminal supports it) which makes them much easier
3333 be colored (if your terminal supports it) which makes them much easier
2937 to parse visually.
3334 to parse visually.
2938
3335
2939 See the magic xmode and colors functions for details (just type %magic).
3336 See the magic xmode and colors functions for details (just type %magic).
2940
3337
2941 These features are basically a terminal version of Ka-Ping Yee's cgitb
3338 These features are basically a terminal version of Ka-Ping Yee's cgitb
2942 module, now part of the standard Python library.
3339 module, now part of the standard Python library.
2943
3340
2944
3341
3342 .. _Input caching:
2945
3343
2946 Input caching system
3344 Input caching system
2947 --------------------
3345 --------------------
2948
3346
2949 IPython offers numbered prompts (In/Out) with input and output caching.
3347 IPython offers numbered prompts (In/Out) with input and output caching.
2950 All input is saved and can be retrieved as variables (besides the usual
3348 All input is saved and can be retrieved as variables (besides the usual
2951 arrow key recall).
3349 arrow key recall).
2952
3350
2953 The following GLOBAL variables always exist (so don't overwrite them!):
3351 The following GLOBAL variables always exist (so don't overwrite them!):
2954 _i: stores previous input. _ii: next previous. _iii: next-next previous.
3352 _i: stores previous input. _ii: next previous. _iii: next-next previous.
2955 _ih : a list of all input _ih[n] is the input from line n and this list
3353 _ih : a list of all input _ih[n] is the input from line n and this list
2956 is aliased to the global variable In. If you overwrite In with a
3354 is aliased to the global variable In. If you overwrite In with a
2957 variable of your own, you can remake the assignment to the internal list
3355 variable of your own, you can remake the assignment to the internal list
2958 with a simple 'In=_ih'.
3356 with a simple 'In=_ih'.
2959
3357
2960 Additionally, global variables named _i<n> are dynamically created (<n>
3358 Additionally, global variables named _i<n> are dynamically created (<n>
2961 being the prompt counter), such that
3359 being the prompt counter), such that
2962 _i<n> == _ih[<n>] == In[<n>].
3360 _i<n> == _ih[<n>] == In[<n>].
2963
3361
2964 For example, what you typed at prompt 14 is available as _i14, _ih[14]
3362 For example, what you typed at prompt 14 is available as _i14, _ih[14]
2965 and In[14].
3363 and In[14].
2966
3364
2967 This allows you to easily cut and paste multi line interactive prompts
3365 This allows you to easily cut and paste multi line interactive prompts
2968 by printing them out: they print like a clean string, without prompt
3366 by printing them out: they print like a clean string, without prompt
2969 characters. You can also manipulate them like regular variables (they
3367 characters. You can also manipulate them like regular variables (they
2970 are strings), modify or exec them (typing 'exec _i9' will re-execute the
3368 are strings), modify or exec them (typing 'exec _i9' will re-execute the
2971 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
3369 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
2972 9 through 13 and line 18).
3370 9 through 13 and line 18).
2973
3371
2974 You can also re-execute multiple lines of input easily by using the
3372 You can also re-execute multiple lines of input easily by using the
2975 magic %macro function (which automates the process and allows
3373 magic %macro function (which automates the process and allows
2976 re-execution without having to type 'exec' every time). The macro system
3374 re-execution without having to type 'exec' every time). The macro system
2977 also allows you to re-execute previous lines which include magic
3375 also allows you to re-execute previous lines which include magic
2978 function calls (which require special processing). Type %macro? or see
3376 function calls (which require special processing). Type %macro? or see
2979 sec. 6.2 <#sec:magic> for more details on the macro system.
3377 sec. 6.2 <#sec:magic> for more details on the macro system.
2980
3378
2981 A history function %hist allows you to see any part of your input
3379 A history function %hist allows you to see any part of your input
2982 history by printing a range of the _i variables.
3380 history by printing a range of the _i variables.
2983
3381
3382 .. _Output caching:
3383
2984 Output caching system
3384 Output caching system
2985 ---------------------
3385 ---------------------
2986
3386
2987 For output that is returned from actions, a system similar to the input
3387 For output that is returned from actions, a system similar to the input
2988 cache exists but using _ instead of _i. Only actions that produce a
3388 cache exists but using _ instead of _i. Only actions that produce a
2989 result (NOT assignments, for example) are cached. If you are familiar
3389 result (NOT assignments, for example) are cached. If you are familiar
2990 with Mathematica, IPython's _ variables behave exactly like
3390 with Mathematica, IPython's _ variables behave exactly like
2991 Mathematica's % variables.
3391 Mathematica's % variables.
2992
3392
2993 The following GLOBAL variables always exist (so don't overwrite them!):
3393 The following GLOBAL variables always exist (so don't overwrite them!):
2994
3394
2995 * [_] (a single underscore) : stores previous output, like Python's
3395 * [_] (a single underscore) : stores previous output, like Python's
2996 default interpreter.
3396 default interpreter.
2997 * [__] (two underscores): next previous.
3397 * [__] (two underscores): next previous.
2998 * [___] (three underscores): next-next previous.
3398 * [___] (three underscores): next-next previous.
2999
3399
3000 Additionally, global variables named _<n> are dynamically created (<n>
3400 Additionally, global variables named _<n> are dynamically created (<n>
3001 being the prompt counter), such that the result of output <n> is always
3401 being the prompt counter), such that the result of output <n> is always
3002 available as _<n> (don't use the angle brackets, just the number, e.g.
3402 available as _<n> (don't use the angle brackets, just the number, e.g.
3003 _21).
3403 _21).
3004
3404
3005 These global variables are all stored in a global dictionary (not a
3405 These global variables are all stored in a global dictionary (not a
3006 list, since it only has entries for lines which returned a result)
3406 list, since it only has entries for lines which returned a result)
3007 available under the names _oh and Out (similar to _ih and In). So the
3407 available under the names _oh and Out (similar to _ih and In). So the
3008 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
3408 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
3009 accidentally overwrite the Out variable you can recover it by typing
3409 accidentally overwrite the Out variable you can recover it by typing
3010 'Out=_oh' at the prompt.
3410 'Out=_oh' at the prompt.
3011
3411
3012 This system obviously can potentially put heavy memory demands on your
3412 This system obviously can potentially put heavy memory demands on your
3013 system, since it prevents Python's garbage collector from removing any
3413 system, since it prevents Python's garbage collector from removing any
3014 previously computed results. You can control how many results are kept
3414 previously computed results. You can control how many results are kept
3015 in memory with the option (at the command line or in your ipythonrc
3415 in memory with the option (at the command line or in your ipythonrc
3016 file) cache_size. If you set it to 0, the whole system is completely
3416 file) cache_size. If you set it to 0, the whole system is completely
3017 disabled and the prompts revert to the classic '>>>' of normal Python.
3417 disabled and the prompts revert to the classic '>>>' of normal Python.
3018
3418
3019
3419
3020 Directory history
3420 Directory history
3021 -----------------
3421 -----------------
3022
3422
3023 Your history of visited directories is kept in the global list _dh, and
3423 Your history of visited directories is kept in the global list _dh, and
3024 the magic %cd command can be used to go to any entry in that list. The
3424 the magic %cd command can be used to go to any entry in that list. The
3025 %dhist command allows you to view this history. do ``cd -<TAB`` to
3425 %dhist command allows you to view this history. do ``cd -<TAB`` to
3026 conventiently view the directory history.
3426 conventiently view the directory history.
3027
3427
3028
3428
3029 Automatic parentheses and quotes
3429 Automatic parentheses and quotes
3030 --------------------------------
3430 --------------------------------
3031
3431
3032 These features were adapted from Nathan Gray's LazyPython. They are
3432 These features were adapted from Nathan Gray's LazyPython. They are
3033 meant to allow less typing for common situations.
3433 meant to allow less typing for common situations.
3034
3434
3035
3435
3036 Automatic parentheses
3436 Automatic parentheses
3037 ---------------------
3437 ---------------------
3038
3438
3039 Callable objects (i.e. functions, methods, etc) can be invoked like this
3439 Callable objects (i.e. functions, methods, etc) can be invoked like this
3040 (notice the commas between the arguments)::
3440 (notice the commas between the arguments)::
3041
3441
3042 >>> callable_ob arg1, arg2, arg3
3442 >>> callable_ob arg1, arg2, arg3
3043
3443
3044 and the input will be translated to this::
3444 and the input will be translated to this::
3045
3445
3046 -> callable_ob(arg1, arg2, arg3)
3446 -> callable_ob(arg1, arg2, arg3)
3047
3447
3048 You can force automatic parentheses by using '/' as the first character
3448 You can force automatic parentheses by using '/' as the first character
3049 of a line. For example::
3449 of a line. For example::
3050
3450
3051 >>> /globals # becomes 'globals()'
3451 >>> /globals # becomes 'globals()'
3052
3452
3053 Note that the '/' MUST be the first character on the line! This won't work::
3453 Note that the '/' MUST be the first character on the line! This won't work::
3054
3454
3055 >>> print /globals # syntax error
3455 >>> print /globals # syntax error
3056
3456
3057 In most cases the automatic algorithm should work, so you should rarely
3457 In most cases the automatic algorithm should work, so you should rarely
3058 need to explicitly invoke /. One notable exception is if you are trying
3458 need to explicitly invoke /. One notable exception is if you are trying
3059 to call a function with a list of tuples as arguments (the parenthesis
3459 to call a function with a list of tuples as arguments (the parenthesis
3060 will confuse IPython)::
3460 will confuse IPython)::
3061
3461
3062 In [1]: zip (1,2,3),(4,5,6) # won't work
3462 In [1]: zip (1,2,3),(4,5,6) # won't work
3063
3463
3064 but this will work::
3464 but this will work::
3065
3465
3066 In [2]: /zip (1,2,3),(4,5,6)
3466 In [2]: /zip (1,2,3),(4,5,6)
3067 ---> zip ((1,2,3),(4,5,6))
3467 ---> zip ((1,2,3),(4,5,6))
3068 Out[2]= [(1, 4), (2, 5), (3, 6)]
3468 Out[2]= [(1, 4), (2, 5), (3, 6)]
3069
3469
3070 IPython tells you that it has altered your command line by displaying
3470 IPython tells you that it has altered your command line by displaying
3071 the new command line preceded by ->. e.g.::
3471 the new command line preceded by ->. e.g.::
3072
3472
3073 In [18]: callable list
3473 In [18]: callable list
3074 ----> callable (list)
3474 ----> callable (list)
3075
3475
3076
3476
3077 Automatic quoting
3477 Automatic quoting
3078 -----------------
3478 -----------------
3079
3479
3080 You can force automatic quoting of a function's arguments by using ','
3480 You can force automatic quoting of a function's arguments by using ','
3081 or ';' as the first character of a line. For example::
3481 or ';' as the first character of a line. For example::
3082
3482
3083 >>> ,my_function /home/me # becomes my_function("/home/me")
3483 >>> ,my_function /home/me # becomes my_function("/home/me")
3084
3484
3085 If you use ';' instead, the whole argument is quoted as a single string
3485 If you use ';' instead, the whole argument is quoted as a single string
3086 (while ',' splits on whitespace)::
3486 (while ',' splits on whitespace)::
3087
3487
3088 >>> ,my_function a b c # becomes my_function("a","b","c")
3488 >>> ,my_function a b c # becomes my_function("a","b","c")
3089
3489
3090 >>> ;my_function a b c # becomes my_function("a b c")
3490 >>> ;my_function a b c # becomes my_function("a b c")
3091
3491
3092 Note that the ',' or ';' MUST be the first character on the line! This
3492 Note that the ',' or ';' MUST be the first character on the line! This
3093 won't work::
3493 won't work::
3094
3494
3095 >>> x = ,my_function /home/me # syntax error
3495 >>> x = ,my_function /home/me # syntax error
3096
3496
3497 .. customization:
3498
3097 Customization
3499 Customization
3098 =============
3500 =============
3099
3501
3100 There are 2 ways to configure IPython - the old way of using ipythonrc
3502 There are 2 ways to configure IPython - the old way of using ipythonrc
3101 files (an INI-file like format), and the new way that involves editing
3503 files (an INI-file like format), and the new way that involves editing
3102 your ipy_user_conf.py. Both configuration systems work at the same
3504 your ipy_user_conf.py. Both configuration systems work at the same
3103 time, so you can set your options in both, but if you are hesitating
3505 time, so you can set your options in both, but if you are hesitating
3104 about which alternative to choose, we recommend the ipy_user_conf.py
3506 about which alternative to choose, we recommend the ipy_user_conf.py
3105 approach, as it will give you more power and control in the long
3507 approach, as it will give you more power and control in the long
3106 run. However, there are few options such as pylab_import_all that can
3508 run. However, there are few options such as pylab_import_all that can
3107 only be specified in ipythonrc file or command line - the reason for
3509 only be specified in ipythonrc file or command line - the reason for
3108 this is that they are needed before IPython has been started up, and
3510 this is that they are needed before IPython has been started up, and
3109 the IPApi object used in ipy_user_conf.py is not yet available at that
3511 the IPApi object used in ipy_user_conf.py is not yet available at that
3110 time. A hybrid approach of specifying a few options in ipythonrc and
3512 time. A hybrid approach of specifying a few options in ipythonrc and
3111 doing the more advanced configuration in ipy_user_conf.py is also
3513 doing the more advanced configuration in ipy_user_conf.py is also
3112 possible.
3514 possible.
3113
3515
3114 The ipythonrc approach
3516 The ipythonrc approach
3115 ----------------------
3517 ----------------------
3116
3518
3117 As we've already mentioned, IPython reads a configuration file which can
3519 As we've already mentioned, IPython reads a configuration file which can
3118 be specified at the command line (-rcfile) or which by default is
3520 be specified at the command line (-rcfile) or which by default is
3119 assumed to be called ipythonrc. Such a file is looked for in the current
3521 assumed to be called ipythonrc. Such a file is looked for in the current
3120 directory where IPython is started and then in your IPYTHONDIR, which
3522 directory where IPython is started and then in your IPYTHONDIR, which
3121 allows you to have local configuration files for specific projects. In
3523 allows you to have local configuration files for specific projects. In
3122 this section we will call these types of configuration files simply
3524 this section we will call these types of configuration files simply
3123 rcfiles (short for resource configuration file).
3525 rcfiles (short for resource configuration file).
3124
3526
3125 The syntax of an rcfile is one of key-value pairs separated by
3527 The syntax of an rcfile is one of key-value pairs separated by
3126 whitespace, one per line. Lines beginning with a # are ignored as
3528 whitespace, one per line. Lines beginning with a # are ignored as
3127 comments, but comments can not be put on lines with data (the parser is
3529 comments, but comments can not be put on lines with data (the parser is
3128 fairly primitive). Note that these are not python files, and this is
3530 fairly primitive). Note that these are not python files, and this is
3129 deliberate, because it allows us to do some things which would be quite
3531 deliberate, because it allows us to do some things which would be quite
3130 tricky to implement if they were normal python files.
3532 tricky to implement if they were normal python files.
3131
3533
3132 First, an rcfile can contain permanent default values for almost all
3534 First, an rcfile can contain permanent default values for almost all
3133 command line options (except things like -help or -Version). Sec 5.2
3535 command line options (except things like -help or -Version). Sec
3134 <node5.html#sec:cmd-line-opts> contains a description of all
3536 `command line options`_ contains a description of all command-line
3135 command-line options. However, values you explicitly specify at the
3537 options. However, values you explicitly specify at the command line
3136 command line override the values defined in the rcfile.
3538 override the values defined in the rcfile.
3137
3539
3138 Besides command line option values, the rcfile can specify values for
3540 Besides command line option values, the rcfile can specify values for
3139 certain extra special options which are not available at the command
3541 certain extra special options which are not available at the command
3140 line. These options are briefly described below.
3542 line. These options are briefly described below.
3141
3543
3142 Each of these options may appear as many times as you need it in the file.
3544 Each of these options may appear as many times as you need it in the file.
3143
3545
3144 * [include <file1> <file2> ...:] you can name other rcfiles you want
3546 * include <file1> <file2> ...: you can name other rcfiles you want
3145 to recursively load up to 15 levels (don't use the <> brackets in
3547 to recursively load up to 15 levels (don't use the <> brackets in
3146 your names!). This feature allows you to define a 'base' rcfile
3548 your names!). This feature allows you to define a 'base' rcfile
3147 with general options and special-purpose files which can be loaded
3549 with general options and special-purpose files which can be loaded
3148 only when needed with particular configuration options. To make
3550 only when needed with particular configuration options. To make
3149 this more convenient, IPython accepts the -profile <name> option
3551 this more convenient, IPython accepts the -profile <name> option
3150 (abbreviates to -p <name>) which tells it to look for an rcfile
3552 (abbreviates to -p <name>) which tells it to look for an rcfile
3151 named ipythonrc-<name>.
3553 named ipythonrc-<name>.
3152 * [import_mod <mod1> <mod2> ...:] import modules with 'import
3554 * import_mod <mod1> <mod2> ...: import modules with 'import
3153 <mod1>,<mod2>,...'
3555 <mod1>,<mod2>,...'
3154 * [import_some <mod> <f1> <f2> ...:] import functions with 'from
3556 * import_some <mod> <f1> <f2> ...: import functions with 'from
3155 <mod> import <f1>,<f2>,...'
3557 <mod> import <f1>,<f2>,...'
3156 * [import_all <mod1> <mod2> ...:] for each module listed import
3558 * import_all <mod1> <mod2> ...: for each module listed import
3157 functions with ``from <mod> import *``.
3559 functions with ``from <mod> import *``.
3158 * [execute <python code>:] give any single-line python code to be
3560 * execute <python code>: give any single-line python code to be
3159 executed.
3561 executed.
3160 * [execfile <filename>:] execute the python file given with an
3562 * execfile <filename>: execute the python file given with an
3161 'execfile(filename)' command. Username expansion is performed on
3563 'execfile(filename)' command. Username expansion is performed on
3162 the given names. So if you need any amount of extra fancy
3564 the given names. So if you need any amount of extra fancy
3163 customization that won't fit in any of the above 'canned' options,
3565 customization that won't fit in any of the above 'canned' options,
3164 you can just put it in a separate python file and execute it.
3566 you can just put it in a separate python file and execute it.
3165 * [alias <alias_def>:] this is equivalent to calling
3567 * alias <alias_def>: this is equivalent to calling
3166 '%alias <alias_def>' at the IPython command line. This way, from
3568 '%alias <alias_def>' at the IPython command line. This way, from
3167 within IPython you can do common system tasks without having to
3569 within IPython you can do common system tasks without having to
3168 exit it or use the ! escape. IPython isn't meant to be a shell
3570 exit it or use the ! escape. IPython isn't meant to be a shell
3169 replacement, but it is often very useful to be able to do things
3571 replacement, but it is often very useful to be able to do things
3170 with files while testing code. This gives you the flexibility to
3572 with files while testing code. This gives you the flexibility to
3171 have within IPython any aliases you may be used to under your
3573 have within IPython any aliases you may be used to under your
3172 normal system shell.
3574 normal system shell.
3173
3575
3174
3576
3577 .. _ipythonrc:
3578
3175 Sample ipythonrc file
3579 Sample ipythonrc file
3176 ---------------------
3580 ---------------------
3177
3581
3178 The default rcfile, called ipythonrc and supplied in your IPYTHONDIR
3582 The default rcfile, called ipythonrc and supplied in your IPYTHONDIR
3179 directory contains lots of comments on all of these options. We
3583 directory contains lots of comments on all of these options. We
3180 reproduce it here for reference::
3584 reproduce it here for reference::
3181
3585
3182
3586
3183 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
3587 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
3184 # $Id: ipythonrc 2156 2007-03-19 02:32:19Z fperez $
3588 # $Id: ipythonrc 2156 2007-03-19 02:32:19Z fperez $
3185
3589
3186 #***************************************************************************
3590 #***************************************************************************
3187 #
3591 #
3188 # Configuration file for IPython -- ipythonrc format
3592 # Configuration file for IPython -- ipythonrc format
3189 #
3593 #
3190 # ===========================================================
3594 # ===========================================================
3191 # Deprecation note: you should look into modifying ipy_user_conf.py (located
3595 # Deprecation note: you should look into modifying ipy_user_conf.py (located
3192 # in ~/.ipython or ~/_ipython, depending on your platform) instead, it's a
3596 # in ~/.ipython or ~/_ipython, depending on your platform) instead, it's a
3193 # more flexible and robust (and better supported!) configuration
3597 # more flexible and robust (and better supported!) configuration
3194 # method.
3598 # method.
3195 # ===========================================================
3599 # ===========================================================
3196 #
3600 #
3197 # The format of this file is simply one of 'key value' lines.
3601 # The format of this file is simply one of 'key value' lines.
3198 # Lines containing only whitespace at the beginning and then a # are ignored
3602 # Lines containing only whitespace at the beginning and then a # are ignored
3199 # as comments. But comments can NOT be put on lines with data.
3603 # as comments. But comments can NOT be put on lines with data.
3200
3604
3201 # The meaning and use of each key are explained below.
3605 # The meaning and use of each key are explained below.
3202
3606
3203 #---------------------------------------------------------------------------
3607 #---------------------------------------------------------------------------
3204 # Section: included files
3608 # Section: included files
3205
3609
3206 # Put one or more *config* files (with the syntax of this file) you want to
3610 # Put one or more *config* files (with the syntax of this file) you want to
3207 # include. For keys with a unique value the outermost file has precedence. For
3611 # include. For keys with a unique value the outermost file has precedence. For
3208 # keys with multiple values, they all get assembled into a list which then
3612 # keys with multiple values, they all get assembled into a list which then
3209 # gets loaded by IPython.
3613 # gets loaded by IPython.
3210
3614
3211 # In this file, all lists of things should simply be space-separated.
3615 # In this file, all lists of things should simply be space-separated.
3212
3616
3213 # This allows you to build hierarchies of files which recursively load
3617 # This allows you to build hierarchies of files which recursively load
3214 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
3618 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
3215 # should only keep here basic things you always want available. Then you can
3619 # should only keep here basic things you always want available. Then you can
3216 # include it in every other special-purpose config file you create.
3620 # include it in every other special-purpose config file you create.
3217 include
3621 include
3218
3622
3219 #---------------------------------------------------------------------------
3623 #---------------------------------------------------------------------------
3220 # Section: startup setup
3624 # Section: startup setup
3221
3625
3222 # These are mostly things which parallel a command line option of the same
3626 # These are mostly things which parallel a command line option of the same
3223 # name.
3627 # name.
3224
3628
3225 # Keys in this section should only appear once. If any key from this section
3629 # Keys in this section should only appear once. If any key from this section
3226 # is encountered more than once, the last value remains, all earlier ones get
3630 # is encountered more than once, the last value remains, all earlier ones get
3227 # discarded.
3631 # discarded.
3228
3632
3229
3633
3230 # Automatic calling of callable objects. If set to 1 or 2, callable objects
3634 # Automatic calling of callable objects. If set to 1 or 2, callable objects
3231 # are automatically called when invoked at the command line, even if you don't
3635 # are automatically called when invoked at the command line, even if you don't
3232 # type parentheses. IPython adds the parentheses for you. For example:
3636 # type parentheses. IPython adds the parentheses for you. For example:
3233
3637
3234 #In [1]: str 45
3638 #In [1]: str 45
3235 #------> str(45)
3639 #------> str(45)
3236 #Out[1]: '45'
3640 #Out[1]: '45'
3237
3641
3238 # IPython reprints your line with '---->' indicating that it added
3642 # IPython reprints your line with '---->' indicating that it added
3239 # parentheses. While this option is very convenient for interactive use, it
3643 # parentheses. While this option is very convenient for interactive use, it
3240 # may occasionally cause problems with objects which have side-effects if
3644 # may occasionally cause problems with objects which have side-effects if
3241 # called unexpectedly.
3645 # called unexpectedly.
3242
3646
3243 # The valid values for autocall are:
3647 # The valid values for autocall are:
3244
3648
3245 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
3649 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
3246
3650
3247 # autocall 1 -> active, but do not apply if there are no arguments on the line.
3651 # autocall 1 -> active, but do not apply if there are no arguments on the line.
3248
3652
3249 # In this mode, you get:
3653 # In this mode, you get:
3250
3654
3251 #In [1]: callable
3655 #In [1]: callable
3252 #Out[1]: <built-in function callable>
3656 #Out[1]: <built-in function callable>
3253
3657
3254 #In [2]: callable 'hello'
3658 #In [2]: callable 'hello'
3255 #------> callable('hello')
3659 #------> callable('hello')
3256 #Out[2]: False
3660 #Out[2]: False
3257
3661
3258 # 2 -> Active always. Even if no arguments are present, the callable object
3662 # 2 -> Active always. Even if no arguments are present, the callable object
3259 # is called:
3663 # is called:
3260
3664
3261 #In [4]: callable
3665 #In [4]: callable
3262 #------> callable()
3666 #------> callable()
3263
3667
3264 # Note that even with autocall off, you can still use '/' at the start of a
3668 # Note that even with autocall off, you can still use '/' at the start of a
3265 # line to treat the first argument on the command line as a function and add
3669 # line to treat the first argument on the command line as a function and add
3266 # parentheses to it:
3670 # parentheses to it:
3267
3671
3268 #In [8]: /str 43
3672 #In [8]: /str 43
3269 #------> str(43)
3673 #------> str(43)
3270 #Out[8]: '43'
3674 #Out[8]: '43'
3271
3675
3272 autocall 1
3676 autocall 1
3273
3677
3274 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
3678 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
3275 # source code (see the 'editor' variable below), it is possible that you save
3679 # source code (see the 'editor' variable below), it is possible that you save
3276 # a file with syntax errors in it. If this variable is true, IPython will ask
3680 # a file with syntax errors in it. If this variable is true, IPython will ask
3277 # you whether to re-open the editor immediately to correct such an error.
3681 # you whether to re-open the editor immediately to correct such an error.
3278
3682
3279 autoedit_syntax 0
3683 autoedit_syntax 0
3280
3684
3281 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
3685 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
3282 # line, while also un-indenting automatically after 'raise' or 'return'.
3686 # line, while also un-indenting automatically after 'raise' or 'return'.
3283
3687
3284 # This feature uses the readline library, so it will honor your ~/.inputrc
3688 # This feature uses the readline library, so it will honor your ~/.inputrc
3285 # configuration (or whatever file your INPUTRC variable points to). Adding
3689 # configuration (or whatever file your INPUTRC variable points to). Adding
3286 # the following lines to your .inputrc file can make indent/unindenting more
3690 # the following lines to your .inputrc file can make indent/unindenting more
3287 # convenient (M-i indents, M-u unindents):
3691 # convenient (M-i indents, M-u unindents):
3288
3692
3289 # $if Python
3693 # $if Python
3290 # "\M-i": " "
3694 # "\M-i": " "
3291 # "\M-u": "\d\d\d\d"
3695 # "\M-u": "\d\d\d\d"
3292 # $endif
3696 # $endif
3293
3697
3294 # The feature is potentially a bit dangerous, because it can cause problems
3698 # The feature is potentially a bit dangerous, because it can cause problems
3295 # with pasting of indented code (the pasted code gets re-indented on each
3699 # with pasting of indented code (the pasted code gets re-indented on each
3296 # line). But it's a huge time-saver when working interactively. The magic
3700 # line). But it's a huge time-saver when working interactively. The magic
3297 # function %autoindent allows you to toggle it on/off at runtime.
3701 # function %autoindent allows you to toggle it on/off at runtime.
3298
3702
3299 autoindent 1
3703 autoindent 1
3300
3704
3301 # Auto-magic. This gives you access to all the magic functions without having
3705 # Auto-magic. This gives you access to all the magic functions without having
3302 # to prepend them with an % sign. If you define a variable with the same name
3706 # to prepend them with an % sign. If you define a variable with the same name
3303 # as a magic function (say who=1), you will need to access the magic function
3707 # as a magic function (say who=1), you will need to access the magic function
3304 # with % (%who in this example). However, if later you delete your variable
3708 # with % (%who in this example). However, if later you delete your variable
3305 # (del who), you'll recover the automagic calling form.
3709 # (del who), you'll recover the automagic calling form.
3306
3710
3307 # Considering that many magic functions provide a lot of shell-like
3711 # Considering that many magic functions provide a lot of shell-like
3308 # functionality, automagic gives you something close to a full Python+system
3712 # functionality, automagic gives you something close to a full Python+system
3309 # shell environment (and you can extend it further if you want).
3713 # shell environment (and you can extend it further if you want).
3310
3714
3311 automagic 1
3715 automagic 1
3312
3716
3313 # Size of the output cache. After this many entries are stored, the cache will
3717 # Size of the output cache. After this many entries are stored, the cache will
3314 # get flushed. Depending on the size of your intermediate calculations, you
3718 # get flushed. Depending on the size of your intermediate calculations, you
3315 # may have memory problems if you make it too big, since keeping things in the
3719 # may have memory problems if you make it too big, since keeping things in the
3316 # cache prevents Python from reclaiming the memory for old results. Experiment
3720 # cache prevents Python from reclaiming the memory for old results. Experiment
3317 # with a value that works well for you.
3721 # with a value that works well for you.
3318
3722
3319 # If you choose cache_size 0 IPython will revert to python's regular >>>
3723 # If you choose cache_size 0 IPython will revert to python's regular >>>
3320 # unnumbered prompt. You will still have _, __ and ___ for your last three
3724 # unnumbered prompt. You will still have _, __ and ___ for your last three
3321 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
3725 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
3322 # you are running on a slow machine or with very limited memory, this may
3726 # you are running on a slow machine or with very limited memory, this may
3323 # help.
3727 # help.
3324
3728
3325 cache_size 1000
3729 cache_size 1000
3326
3730
3327 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
3731 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
3328 # but that's your choice! Classic 1 -> same as IPython -classic.
3732 # but that's your choice! Classic 1 -> same as IPython -classic.
3329 # Note that this is _not_ the normal python interpreter, it's simply
3733 # Note that this is _not_ the normal python interpreter, it's simply
3330 # IPython emulating most of the classic interpreter's behavior.
3734 # IPython emulating most of the classic interpreter's behavior.
3331 classic 0
3735 classic 0
3332
3736
3333 # colors - Coloring option for prompts and traceback printouts.
3737 # colors - Coloring option for prompts and traceback printouts.
3334
3738
3335 # Currently available schemes: NoColor, Linux, LightBG.
3739 # Currently available schemes: NoColor, Linux, LightBG.
3336
3740
3337 # This option allows coloring the prompts and traceback printouts. This
3741 # This option allows coloring the prompts and traceback printouts. This
3338 # requires a terminal which can properly handle color escape sequences. If you
3742 # requires a terminal which can properly handle color escape sequences. If you
3339 # are having problems with this, use the NoColor scheme (uses no color escapes
3743 # are having problems with this, use the NoColor scheme (uses no color escapes
3340 # at all).
3744 # at all).
3341
3745
3342 # The Linux option works well in linux console type environments: dark
3746 # The Linux option works well in linux console type environments: dark
3343 # background with light fonts.
3747 # background with light fonts.
3344
3748
3345 # LightBG is similar to Linux but swaps dark/light colors to be more readable
3749 # LightBG is similar to Linux but swaps dark/light colors to be more readable
3346 # in light background terminals.
3750 # in light background terminals.
3347
3751
3348 # keep uncommented only the one you want:
3752 # keep uncommented only the one you want:
3349 colors Linux
3753 colors Linux
3350 #colors LightBG
3754 #colors LightBG
3351 #colors NoColor
3755 #colors NoColor
3352
3756
3353 ########################
3757 ########################
3354 # Note to Windows users
3758 # Note to Windows users
3355 #
3759 #
3356 # Color and readline support is avaialble to Windows users via Gary Bishop's
3760 # Color and readline support is avaialble to Windows users via Gary Bishop's
3357 # readline library. You can find Gary's tools at
3761 # readline library. You can find Gary's tools at
3358 # http://sourceforge.net/projects/uncpythontools.
3762 # http://sourceforge.net/projects/uncpythontools.
3359 # Note that his readline module requires in turn the ctypes library, available
3763 # Note that his readline module requires in turn the ctypes library, available
3360 # at http://starship.python.net/crew/theller/ctypes.
3764 # at http://starship.python.net/crew/theller/ctypes.
3361 ########################
3765 ########################
3362
3766
3363 # color_info: IPython can display information about objects via a set of
3767 # color_info: IPython can display information about objects via a set of
3364 # functions, and optionally can use colors for this, syntax highlighting
3768 # functions, and optionally can use colors for this, syntax highlighting
3365 # source code and various other elements. This information is passed through a
3769 # source code and various other elements. This information is passed through a
3366 # pager (it defaults to 'less' if $PAGER is not set).
3770 # pager (it defaults to 'less' if $PAGER is not set).
3367
3771
3368 # If your pager has problems, try to setting it to properly handle escapes
3772 # If your pager has problems, try to setting it to properly handle escapes
3369 # (see the less manpage for detail), or disable this option. The magic
3773 # (see the less manpage for detail), or disable this option. The magic
3370 # function %color_info allows you to toggle this interactively for testing.
3774 # function %color_info allows you to toggle this interactively for testing.
3371
3775
3372 color_info 1
3776 color_info 1
3373
3777
3374 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
3778 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
3375 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
3779 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
3376 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
3780 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
3377 # any confirmation.
3781 # any confirmation.
3378
3782
3379 confirm_exit 1
3783 confirm_exit 1
3380
3784
3381 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
3785 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
3382 # still available as dreload() and appears as a builtin.
3786 # still available as dreload() and appears as a builtin.
3383
3787
3384 deep_reload 0
3788 deep_reload 0
3385
3789
3386 # Which editor to use with the %edit command. If you leave this at 0, IPython
3790 # Which editor to use with the %edit command. If you leave this at 0, IPython
3387 # will honor your EDITOR environment variable. Since this editor is invoked on
3791 # will honor your EDITOR environment variable. Since this editor is invoked on
3388 # the fly by ipython and is meant for editing small code snippets, you may
3792 # the fly by ipython and is meant for editing small code snippets, you may
3389 # want to use a small, lightweight editor here.
3793 # want to use a small, lightweight editor here.
3390
3794
3391 # For Emacs users, setting up your Emacs server properly as described in the
3795 # For Emacs users, setting up your Emacs server properly as described in the
3392 # manual is a good idea. An alternative is to use jed, a very light editor
3796 # manual is a good idea. An alternative is to use jed, a very light editor
3393 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
3797 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
3394
3798
3395 editor 0
3799 editor 0
3396
3800
3397 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
3801 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
3398 log 0
3802 log 0
3399
3803
3400 # Same as ipython -Logfile YourLogfileName.
3804 # Same as ipython -Logfile YourLogfileName.
3401 # Don't use with log 1 (use one or the other)
3805 # Don't use with log 1 (use one or the other)
3402 logfile ''
3806 logfile ''
3403
3807
3404 # banner 0 -> same as ipython -nobanner
3808 # banner 0 -> same as ipython -nobanner
3405 banner 1
3809 banner 1
3406
3810
3407 # messages 0 -> same as ipython -nomessages
3811 # messages 0 -> same as ipython -nomessages
3408 messages 1
3812 messages 1
3409
3813
3410 # Automatically call the pdb debugger after every uncaught exception. If you
3814 # Automatically call the pdb debugger after every uncaught exception. If you
3411 # are used to debugging using pdb, this puts you automatically inside of it
3815 # are used to debugging using pdb, this puts you automatically inside of it
3412 # after any call (either in IPython or in code called by it) which triggers an
3816 # after any call (either in IPython or in code called by it) which triggers an
3413 # exception which goes uncaught.
3817 # exception which goes uncaught.
3414 pdb 0
3818 pdb 0
3415
3819
3416 # Enable the pprint module for printing. pprint tends to give a more readable
3820 # Enable the pprint module for printing. pprint tends to give a more readable
3417 # display (than print) for complex nested data structures.
3821 # display (than print) for complex nested data structures.
3418 pprint 1
3822 pprint 1
3419
3823
3420 # Prompt strings
3824 # Prompt strings
3421
3825
3422 # Most bash-like escapes can be used to customize IPython's prompts, as well as
3826 # Most bash-like escapes can be used to customize IPython's prompts, as well as
3423 # a few additional ones which are IPython-specific. All valid prompt escapes
3827 # a few additional ones which are IPython-specific. All valid prompt escapes
3424 # are described in detail in the Customization section of the IPython HTML/PDF
3828 # are described in detail in the Customization section of the IPython HTML/PDF
3425 # manual.
3829 # manual.
3426
3830
3427 # Use \# to represent the current prompt number, and quote them to protect
3831 # Use \# to represent the current prompt number, and quote them to protect
3428 # spaces.
3832 # spaces.
3429 prompt_in1 'In [\#]: '
3833 prompt_in1 'In [\#]: '
3430
3834
3431 # \D is replaced by as many dots as there are digits in the
3835 # \D is replaced by as many dots as there are digits in the
3432 # current value of \#.
3836 # current value of \#.
3433 prompt_in2 ' .\D.: '
3837 prompt_in2 ' .\D.: '
3434
3838
3435 prompt_out 'Out[\#]: '
3839 prompt_out 'Out[\#]: '
3436
3840
3437 # Select whether to left-pad the output prompts to match the length of the
3841 # Select whether to left-pad the output prompts to match the length of the
3438 # input ones. This allows you for example to use a simple '>' as an output
3842 # input ones. This allows you for example to use a simple '>' as an output
3439 # prompt, and yet have the output line up with the input. If set to false,
3843 # prompt, and yet have the output line up with the input. If set to false,
3440 # the output prompts will be unpadded (flush left).
3844 # the output prompts will be unpadded (flush left).
3441 prompts_pad_left 1
3845 prompts_pad_left 1
3442
3846
3443 # Pylab support: when ipython is started with the -pylab switch, by default it
3847 # Pylab support: when ipython is started with the -pylab switch, by default it
3444 # executes 'from matplotlib.pylab import *'. Set this variable to false if you
3848 # executes 'from matplotlib.pylab import *'. Set this variable to false if you
3445 # want to disable this behavior.
3849 # want to disable this behavior.
3446
3850
3447 # For details on pylab, see the matplotlib website:
3851 # For details on pylab, see the matplotlib website:
3448 # http://matplotlib.sf.net
3852 # http://matplotlib.sf.net
3449 pylab_import_all 1
3853 pylab_import_all 1
3450
3854
3451
3855
3452 # quick 1 -> same as ipython -quick
3856 # quick 1 -> same as ipython -quick
3453 quick 0
3857 quick 0
3454
3858
3455 # Use the readline library (1) or not (0). Most users will want this on, but
3859 # Use the readline library (1) or not (0). Most users will want this on, but
3456 # if you experience strange problems with line management (mainly when using
3860 # if you experience strange problems with line management (mainly when using
3457 # IPython inside Emacs buffers) you may try disabling it. Not having it on
3861 # IPython inside Emacs buffers) you may try disabling it. Not having it on
3458 # prevents you from getting command history with the arrow keys, searching and
3862 # prevents you from getting command history with the arrow keys, searching and
3459 # name completion using TAB.
3863 # name completion using TAB.
3460
3864
3461 readline 1
3865 readline 1
3462
3866
3463 # Screen Length: number of lines of your screen. This is used to control
3867 # Screen Length: number of lines of your screen. This is used to control
3464 # printing of very long strings. Strings longer than this number of lines will
3868 # printing of very long strings. Strings longer than this number of lines will
3465 # be paged with the less command instead of directly printed.
3869 # be paged with the less command instead of directly printed.
3466
3870
3467 # The default value for this is 0, which means IPython will auto-detect your
3871 # The default value for this is 0, which means IPython will auto-detect your
3468 # screen size every time it needs to print. If for some reason this isn't
3872 # screen size every time it needs to print. If for some reason this isn't
3469 # working well (it needs curses support), specify it yourself. Otherwise don't
3873 # working well (it needs curses support), specify it yourself. Otherwise don't
3470 # change the default.
3874 # change the default.
3471
3875
3472 screen_length 0
3876 screen_length 0
3473
3877
3474 # Prompt separators for input and output.
3878 # Prompt separators for input and output.
3475 # Use \n for newline explicitly, without quotes.
3879 # Use \n for newline explicitly, without quotes.
3476 # Use 0 (like at the cmd line) to turn off a given separator.
3880 # Use 0 (like at the cmd line) to turn off a given separator.
3477
3881
3478 # The structure of prompt printing is:
3882 # The structure of prompt printing is:
3479 # (SeparateIn)Input....
3883 # (SeparateIn)Input....
3480 # (SeparateOut)Output...
3884 # (SeparateOut)Output...
3481 # (SeparateOut2), # that is, no newline is printed after Out2
3885 # (SeparateOut2), # that is, no newline is printed after Out2
3482 # By choosing these you can organize your output any way you want.
3886 # By choosing these you can organize your output any way you want.
3483
3887
3484 separate_in \n
3888 separate_in \n
3485 separate_out 0
3889 separate_out 0
3486 separate_out2 0
3890 separate_out2 0
3487
3891
3488 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
3892 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
3489 # Simply removes all input/output separators, overriding the choices above.
3893 # Simply removes all input/output separators, overriding the choices above.
3490 nosep 0
3894 nosep 0
3491
3895
3492 # Wildcard searches - IPython has a system for searching names using
3896 # Wildcard searches - IPython has a system for searching names using
3493 # shell-like wildcards; type %psearch? for details. This variables sets
3897 # shell-like wildcards; type %psearch? for details. This variables sets
3494 # whether by default such searches should be case sensitive or not. You can
3898 # whether by default such searches should be case sensitive or not. You can
3495 # always override the default at the system command line or the IPython
3899 # always override the default at the system command line or the IPython
3496 # prompt.
3900 # prompt.
3497
3901
3498 wildcards_case_sensitive 1
3902 wildcards_case_sensitive 1
3499
3903
3500 # Object information: at what level of detail to display the string form of an
3904 # Object information: at what level of detail to display the string form of an
3501 # object. If set to 0, ipython will compute the string form of any object X,
3905 # object. If set to 0, ipython will compute the string form of any object X,
3502 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
3906 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
3503 # computed when X?? is given, and if set to 2 or higher, it will never be
3907 # computed when X?? is given, and if set to 2 or higher, it will never be
3504 # computed (there is no X??? level of detail). This is mostly of use to
3908 # computed (there is no X??? level of detail). This is mostly of use to
3505 # people who frequently manipulate objects whose string representation is
3909 # people who frequently manipulate objects whose string representation is
3506 # extremely expensive to compute.
3910 # extremely expensive to compute.
3507
3911
3508 object_info_string_level 0
3912 object_info_string_level 0
3509
3913
3510 # xmode - Exception reporting mode.
3914 # xmode - Exception reporting mode.
3511
3915
3512 # Valid modes: Plain, Context and Verbose.
3916 # Valid modes: Plain, Context and Verbose.
3513
3917
3514 # Plain: similar to python's normal traceback printing.
3918 # Plain: similar to python's normal traceback printing.
3515
3919
3516 # Context: prints 5 lines of context source code around each line in the
3920 # Context: prints 5 lines of context source code around each line in the
3517 # traceback.
3921 # traceback.
3518
3922
3519 # Verbose: similar to Context, but additionally prints the variables currently
3923 # Verbose: similar to Context, but additionally prints the variables currently
3520 # visible where the exception happened (shortening their strings if too
3924 # visible where the exception happened (shortening their strings if too
3521 # long). This can potentially be very slow, if you happen to have a huge data
3925 # long). This can potentially be very slow, if you happen to have a huge data
3522 # structure whose string representation is complex to compute. Your computer
3926 # structure whose string representation is complex to compute. Your computer
3523 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
3927 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
3524 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
3928 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
3525
3929
3526 #xmode Plain
3930 #xmode Plain
3527 xmode Context
3931 xmode Context
3528 #xmode Verbose
3932 #xmode Verbose
3529
3933
3530 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
3934 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
3531 # !cmd) to be used in multi-line input (like for loops). For example, if you
3935 # !cmd) to be used in multi-line input (like for loops). For example, if you
3532 # have this active, the following is valid in IPython:
3936 # have this active, the following is valid in IPython:
3533 #
3937 #
3534 #In [17]: for i in range(3):
3938 #In [17]: for i in range(3):
3535 # ....: mkdir $i
3939 # ....: mkdir $i
3536 # ....: !touch $i/hello
3940 # ....: !touch $i/hello
3537 # ....: ls -l $i
3941 # ....: ls -l $i
3538
3942
3539 multi_line_specials 1
3943 multi_line_specials 1
3540
3944
3541
3945
3542 # System calls: When IPython makes system calls (e.g. via special syntax like
3946 # System calls: When IPython makes system calls (e.g. via special syntax like
3543 # !cmd or !!cmd, or magics like %sc or %sx), it can print the command it is
3947 # !cmd or !!cmd, or magics like %sc or %sx), it can print the command it is
3544 # executing to standard output, prefixed by a header string.
3948 # executing to standard output, prefixed by a header string.
3545
3949
3546 system_header "IPython system call: "
3950 system_header "IPython system call: "
3547
3951
3548 system_verbose 1
3952 system_verbose 1
3549
3953
3550 # wxversion: request a specific wxPython version (used for -wthread)
3954 # wxversion: request a specific wxPython version (used for -wthread)
3551
3955
3552 # Set this to the value of wxPython you want to use, but note that this
3956 # Set this to the value of wxPython you want to use, but note that this
3553 # feature requires you to have the wxversion Python module to work. If you
3957 # feature requires you to have the wxversion Python module to work. If you
3554 # don't have the wxversion module (try 'import wxversion' at the prompt to
3958 # don't have the wxversion module (try 'import wxversion' at the prompt to
3555 # check) or simply want to leave the system to pick up the default, leave this
3959 # check) or simply want to leave the system to pick up the default, leave this
3556 # variable at 0.
3960 # variable at 0.
3557
3961
3558 wxversion 0
3962 wxversion 0
3559
3963
3560 #---------------------------------------------------------------------------
3964 #---------------------------------------------------------------------------
3561 # Section: Readline configuration (readline is not available for MS-Windows)
3965 # Section: Readline configuration (readline is not available for MS-Windows)
3562
3966
3563 # This is done via the following options:
3967 # This is done via the following options:
3564
3968
3565 # (i) readline_parse_and_bind: this option can appear as many times as you
3969 # (i) readline_parse_and_bind: this option can appear as many times as you
3566 # want, each time defining a string to be executed via a
3970 # want, each time defining a string to be executed via a
3567 # readline.parse_and_bind() command. The syntax for valid commands of this
3971 # readline.parse_and_bind() command. The syntax for valid commands of this
3568 # kind can be found by reading the documentation for the GNU readline library,
3972 # kind can be found by reading the documentation for the GNU readline library,
3569 # as these commands are of the kind which readline accepts in its
3973 # as these commands are of the kind which readline accepts in its
3570 # configuration file.
3974 # configuration file.
3571
3975
3572 # The TAB key can be used to complete names at the command line in one of two
3976 # The TAB key can be used to complete names at the command line in one of two
3573 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
3977 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
3574 # completes as much as possible while 'menu-complete' cycles through all
3978 # completes as much as possible while 'menu-complete' cycles through all
3575 # possible completions. Leave the one you prefer uncommented.
3979 # possible completions. Leave the one you prefer uncommented.
3576
3980
3577 readline_parse_and_bind tab: complete
3981 readline_parse_and_bind tab: complete
3578 #readline_parse_and_bind tab: menu-complete
3982 #readline_parse_and_bind tab: menu-complete
3579
3983
3580 # This binds Control-l to printing the list of all possible completions when
3984 # This binds Control-l to printing the list of all possible completions when
3581 # there is more than one (what 'complete' does when hitting TAB twice, or at
3985 # there is more than one (what 'complete' does when hitting TAB twice, or at
3582 # the first TAB if show-all-if-ambiguous is on)
3986 # the first TAB if show-all-if-ambiguous is on)
3583 readline_parse_and_bind "\C-l": possible-completions
3987 readline_parse_and_bind "\C-l": possible-completions
3584
3988
3585 # This forces readline to automatically print the above list when tab
3989 # This forces readline to automatically print the above list when tab
3586 # completion is set to 'complete'. You can still get this list manually by
3990 # completion is set to 'complete'. You can still get this list manually by
3587 # using the key bound to 'possible-completions' (Control-l by default) or by
3991 # using the key bound to 'possible-completions' (Control-l by default) or by
3588 # hitting TAB twice. Turning this on makes the printing happen at the first
3992 # hitting TAB twice. Turning this on makes the printing happen at the first
3589 # TAB.
3993 # TAB.
3590 readline_parse_and_bind set show-all-if-ambiguous on
3994 readline_parse_and_bind set show-all-if-ambiguous on
3591
3995
3592 # If you have TAB set to complete names, you can rebind any key (Control-o by
3996 # If you have TAB set to complete names, you can rebind any key (Control-o by
3593 # default) to insert a true TAB character.
3997 # default) to insert a true TAB character.
3594 readline_parse_and_bind "\C-o": tab-insert
3998 readline_parse_and_bind "\C-o": tab-insert
3595
3999
3596 # These commands allow you to indent/unindent easily, with the 4-space
4000 # These commands allow you to indent/unindent easily, with the 4-space
3597 # convention of the Python coding standards. Since IPython's internal
4001 # convention of the Python coding standards. Since IPython's internal
3598 # auto-indent system also uses 4 spaces, you should not change the number of
4002 # auto-indent system also uses 4 spaces, you should not change the number of
3599 # spaces in the code below.
4003 # spaces in the code below.
3600 readline_parse_and_bind "\M-i": " "
4004 readline_parse_and_bind "\M-i": " "
3601 readline_parse_and_bind "\M-o": "\d\d\d\d"
4005 readline_parse_and_bind "\M-o": "\d\d\d\d"
3602 readline_parse_and_bind "\M-I": "\d\d\d\d"
4006 readline_parse_and_bind "\M-I": "\d\d\d\d"
3603
4007
3604 # Bindings for incremental searches in the history. These searches use the
4008 # Bindings for incremental searches in the history. These searches use the
3605 # string typed so far on the command line and search anything in the previous
4009 # string typed so far on the command line and search anything in the previous
3606 # input history containing them.
4010 # input history containing them.
3607 readline_parse_and_bind "\C-r": reverse-search-history
4011 readline_parse_and_bind "\C-r": reverse-search-history
3608 readline_parse_and_bind "\C-s": forward-search-history
4012 readline_parse_and_bind "\C-s": forward-search-history
3609
4013
3610 # Bindings for completing the current line in the history of previous
4014 # Bindings for completing the current line in the history of previous
3611 # commands. This allows you to recall any previous command by typing its first
4015 # commands. This allows you to recall any previous command by typing its first
3612 # few letters and hitting Control-p, bypassing all intermediate commands which
4016 # few letters and hitting Control-p, bypassing all intermediate commands which
3613 # may be in the history (much faster than hitting up-arrow 50 times!)
4017 # may be in the history (much faster than hitting up-arrow 50 times!)
3614 readline_parse_and_bind "\C-p": history-search-backward
4018 readline_parse_and_bind "\C-p": history-search-backward
3615 readline_parse_and_bind "\C-n": history-search-forward
4019 readline_parse_and_bind "\C-n": history-search-forward
3616
4020
3617 # I also like to have the same functionality on the plain arrow keys. If you'd
4021 # I also like to have the same functionality on the plain arrow keys. If you'd
3618 # rather have the arrows use all the history (and not just match what you've
4022 # rather have the arrows use all the history (and not just match what you've
3619 # typed so far), comment out or delete the next two lines.
4023 # typed so far), comment out or delete the next two lines.
3620 readline_parse_and_bind "\e[A": history-search-backward
4024 readline_parse_and_bind "\e[A": history-search-backward
3621 readline_parse_and_bind "\e[B": history-search-forward
4025 readline_parse_and_bind "\e[B": history-search-forward
3622
4026
3623 # These are typically on by default under *nix, but not win32.
4027 # These are typically on by default under *nix, but not win32.
3624 readline_parse_and_bind "\C-k": kill-line
4028 readline_parse_and_bind "\C-k": kill-line
3625 readline_parse_and_bind "\C-u": unix-line-discard
4029 readline_parse_and_bind "\C-u": unix-line-discard
3626
4030
3627 # (ii) readline_remove_delims: a string of characters to be removed from the
4031 # (ii) readline_remove_delims: a string of characters to be removed from the
3628 # default word-delimiters list used by readline, so that completions may be
4032 # default word-delimiters list used by readline, so that completions may be
3629 # performed on strings which contain them.
4033 # performed on strings which contain them.
3630
4034
3631 readline_remove_delims -/~
4035 readline_remove_delims -/~
3632
4036
3633 # (iii) readline_merge_completions: whether to merge the result of all
4037 # (iii) readline_merge_completions: whether to merge the result of all
3634 # possible completions or not. If true, IPython will complete filenames,
4038 # possible completions or not. If true, IPython will complete filenames,
3635 # python names and aliases and return all possible completions. If you set it
4039 # python names and aliases and return all possible completions. If you set it
3636 # to false, each completer is used at a time, and only if it doesn't return
4040 # to false, each completer is used at a time, and only if it doesn't return
3637 # any completions is the next one used.
4041 # any completions is the next one used.
3638
4042
3639 # The default order is: [python_matches, file_matches, alias_matches]
4043 # The default order is: [python_matches, file_matches, alias_matches]
3640
4044
3641 readline_merge_completions 1
4045 readline_merge_completions 1
3642
4046
3643 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
4047 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
3644 # will complete all attributes of an object, including all the special methods
4048 # will complete all attributes of an object, including all the special methods
3645 # whose names start with single or double underscores (like __getitem__ or
4049 # whose names start with single or double underscores (like __getitem__ or
3646 # __class__).
4050 # __class__).
3647
4051
3648 # This variable allows you to control this completion behavior:
4052 # This variable allows you to control this completion behavior:
3649
4053
3650 # readline_omit__names 1 -> completion will omit showing any names starting
4054 # readline_omit__names 1 -> completion will omit showing any names starting
3651 # with two __, but it will still show names starting with one _.
4055 # with two __, but it will still show names starting with one _.
3652
4056
3653 # readline_omit__names 2 -> completion will omit all names beginning with one
4057 # readline_omit__names 2 -> completion will omit all names beginning with one
3654 # _ (which obviously means filtering out the double __ ones).
4058 # _ (which obviously means filtering out the double __ ones).
3655
4059
3656 # Even when this option is set, you can still see those names by explicitly
4060 # Even when this option is set, you can still see those names by explicitly
3657 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
4061 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
3658 # complete attribute names starting with '_'.
4062 # complete attribute names starting with '_'.
3659
4063
3660 # This option is off by default so that new users see all attributes of any
4064 # This option is off by default so that new users see all attributes of any
3661 # objects they are dealing with.
4065 # objects they are dealing with.
3662
4066
3663 readline_omit__names 0
4067 readline_omit__names 0
3664
4068
3665 #---------------------------------------------------------------------------
4069 #---------------------------------------------------------------------------
3666 # Section: modules to be loaded with 'import ...'
4070 # Section: modules to be loaded with 'import ...'
3667
4071
3668 # List, separated by spaces, the names of the modules you want to import
4072 # List, separated by spaces, the names of the modules you want to import
3669
4073
3670 # Example:
4074 # Example:
3671 # import_mod sys os
4075 # import_mod sys os
3672 # will produce internally the statements
4076 # will produce internally the statements
3673 # import sys
4077 # import sys
3674 # import os
4078 # import os
3675
4079
3676 # Each import is executed in its own try/except block, so if one module
4080 # Each import is executed in its own try/except block, so if one module
3677 # fails to load the others will still be ok.
4081 # fails to load the others will still be ok.
3678
4082
3679 import_mod
4083 import_mod
3680
4084
3681 #---------------------------------------------------------------------------
4085 #---------------------------------------------------------------------------
3682 # Section: modules to import some functions from: 'from ... import ...'
4086 # Section: modules to import some functions from: 'from ... import ...'
3683
4087
3684 # List, one per line, the modules for which you want only to import some
4088 # List, one per line, the modules for which you want only to import some
3685 # functions. Give the module name first and then the name of functions to be
4089 # functions. Give the module name first and then the name of functions to be
3686 # imported from that module.
4090 # imported from that module.
3687
4091
3688 # Example:
4092 # Example:
3689
4093
3690 # import_some IPython.genutils timing timings
4094 # import_some IPython.genutils timing timings
3691 # will produce internally the statement
4095 # will produce internally the statement
3692 # from IPython.genutils import timing, timings
4096 # from IPython.genutils import timing, timings
3693
4097
3694 # timing() and timings() are two IPython utilities for timing the execution of
4098 # timing() and timings() are two IPython utilities for timing the execution of
3695 # your own functions, which you may find useful. Just commment out the above
4099 # your own functions, which you may find useful. Just commment out the above
3696 # line if you want to test them.
4100 # line if you want to test them.
3697
4101
3698 # If you have more than one modules_some line, each gets its own try/except
4102 # If you have more than one modules_some line, each gets its own try/except
3699 # block (like modules, see above).
4103 # block (like modules, see above).
3700
4104
3701 import_some
4105 import_some
3702
4106
3703 #---------------------------------------------------------------------------
4107 #---------------------------------------------------------------------------
3704 # Section: modules to import all from : 'from ... import *'
4108 # Section: modules to import all from : 'from ... import *'
3705
4109
3706 # List (same syntax as import_mod above) those modules for which you want to
4110 # List (same syntax as import_mod above) those modules for which you want to
3707 # import all functions. Remember, this is a potentially dangerous thing to do,
4111 # import all functions. Remember, this is a potentially dangerous thing to do,
3708 # since it is very easy to overwrite names of things you need. Use with
4112 # since it is very easy to overwrite names of things you need. Use with
3709 # caution.
4113 # caution.
3710
4114
3711 # Example:
4115 # Example:
3712 # import_all sys os
4116 # import_all sys os
3713 # will produce internally the statements
4117 # will produce internally the statements
3714 # from sys import *
4118 # from sys import *
3715 # from os import *
4119 # from os import *
3716
4120
3717 # As before, each will be called in a separate try/except block.
4121 # As before, each will be called in a separate try/except block.
3718
4122
3719 import_all
4123 import_all
3720
4124
3721 #---------------------------------------------------------------------------
4125 #---------------------------------------------------------------------------
3722 # Section: Python code to execute.
4126 # Section: Python code to execute.
3723
4127
3724 # Put here code to be explicitly executed (keep it simple!)
4128 # Put here code to be explicitly executed (keep it simple!)
3725 # Put one line of python code per line. All whitespace is removed (this is a
4129 # Put one line of python code per line. All whitespace is removed (this is a
3726 # feature, not a bug), so don't get fancy building loops here.
4130 # feature, not a bug), so don't get fancy building loops here.
3727 # This is just for quick convenient creation of things you want available.
4131 # This is just for quick convenient creation of things you want available.
3728
4132
3729 # Example:
4133 # Example:
3730 # execute x = 1
4134 # execute x = 1
3731 # execute print 'hello world'; y = z = 'a'
4135 # execute print 'hello world'; y = z = 'a'
3732 # will produce internally
4136 # will produce internally
3733 # x = 1
4137 # x = 1
3734 # print 'hello world'; y = z = 'a'
4138 # print 'hello world'; y = z = 'a'
3735 # and each *line* (not each statement, we don't do python syntax parsing) is
4139 # and each *line* (not each statement, we don't do python syntax parsing) is
3736 # executed in its own try/except block.
4140 # executed in its own try/except block.
3737
4141
3738 execute
4142 execute
3739
4143
3740 # Note for the adventurous: you can use this to define your own names for the
4144 # Note for the adventurous: you can use this to define your own names for the
3741 # magic functions, by playing some namespace tricks:
4145 # magic functions, by playing some namespace tricks:
3742
4146
3743 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
4147 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
3744
4148
3745 # defines %pf as a new name for %profile.
4149 # defines %pf as a new name for %profile.
3746
4150
3747 #---------------------------------------------------------------------------
4151 #---------------------------------------------------------------------------
3748 # Section: Pyhton files to load and execute.
4152 # Section: Pyhton files to load and execute.
3749
4153
3750 # Put here the full names of files you want executed with execfile(file). If
4154 # Put here the full names of files you want executed with execfile(file). If
3751 # you want complicated initialization, just write whatever you want in a
4155 # you want complicated initialization, just write whatever you want in a
3752 # regular python file and load it from here.
4156 # regular python file and load it from here.
3753
4157
3754 # Filenames defined here (which *must* include the extension) are searched for
4158 # Filenames defined here (which *must* include the extension) are searched for
3755 # through all of sys.path. Since IPython adds your .ipython directory to
4159 # through all of sys.path. Since IPython adds your .ipython directory to
3756 # sys.path, they can also be placed in your .ipython dir and will be
4160 # sys.path, they can also be placed in your .ipython dir and will be
3757 # found. Otherwise (if you want to execute things not in .ipyton nor in
4161 # found. Otherwise (if you want to execute things not in .ipyton nor in
3758 # sys.path) give a full path (you can use ~, it gets expanded)
4162 # sys.path) give a full path (you can use ~, it gets expanded)
3759
4163
3760 # Example:
4164 # Example:
3761 # execfile file1.py ~/file2.py
4165 # execfile file1.py ~/file2.py
3762 # will generate
4166 # will generate
3763 # execfile('file1.py')
4167 # execfile('file1.py')
3764 # execfile('_path_to_your_home/file2.py')
4168 # execfile('_path_to_your_home/file2.py')
3765
4169
3766 # As before, each file gets its own try/except block.
4170 # As before, each file gets its own try/except block.
3767
4171
3768 execfile
4172 execfile
3769
4173
3770 # If you are feeling adventurous, you can even add functionality to IPython
4174 # If you are feeling adventurous, you can even add functionality to IPython
3771 # through here. IPython works through a global variable called __ip which
4175 # through here. IPython works through a global variable called __ip which
3772 # exists at the time when these files are read. If you know what you are doing
4176 # exists at the time when these files are read. If you know what you are doing
3773 # (read the source) you can add functions to __ip in files loaded here.
4177 # (read the source) you can add functions to __ip in files loaded here.
3774
4178
3775 # The file example-magic.py contains a simple but correct example. Try it:
4179 # The file example-magic.py contains a simple but correct example. Try it:
3776
4180
3777 # execfile example-magic.py
4181 # execfile example-magic.py
3778
4182
3779 # Look at the examples in IPython/iplib.py for more details on how these magic
4183 # Look at the examples in IPython/iplib.py for more details on how these magic
3780 # functions need to process their arguments.
4184 # functions need to process their arguments.
3781
4185
3782 #---------------------------------------------------------------------------
4186 #---------------------------------------------------------------------------
3783 # Section: aliases for system shell commands
4187 # Section: aliases for system shell commands
3784
4188
3785 # Here you can define your own names for system commands. The syntax is
4189 # Here you can define your own names for system commands. The syntax is
3786 # similar to that of the builtin %alias function:
4190 # similar to that of the builtin %alias function:
3787
4191
3788 # alias alias_name command_string
4192 # alias alias_name command_string
3789
4193
3790 # The resulting aliases are auto-generated magic functions (hence usable as
4194 # The resulting aliases are auto-generated magic functions (hence usable as
3791 # %alias_name)
4195 # %alias_name)
3792
4196
3793 # For example:
4197 # For example:
3794
4198
3795 # alias myls ls -la
4199 # alias myls ls -la
3796
4200
3797 # will define 'myls' as an alias for executing the system command 'ls -la'.
4201 # will define 'myls' as an alias for executing the system command 'ls -la'.
3798 # This allows you to customize IPython's environment to have the same aliases
4202 # This allows you to customize IPython's environment to have the same aliases
3799 # you are accustomed to from your own shell.
4203 # you are accustomed to from your own shell.
3800
4204
3801 # You can also define aliases with parameters using %s specifiers (one per
4205 # You can also define aliases with parameters using %s specifiers (one per
3802 # parameter):
4206 # parameter):
3803
4207
3804 # alias parts echo first %s second %s
4208 # alias parts echo first %s second %s
3805
4209
3806 # will give you in IPython:
4210 # will give you in IPython:
3807 # >>> %parts A B
4211 # >>> %parts A B
3808 # first A second B
4212 # first A second B
3809
4213
3810 # Use one 'alias' statement per alias you wish to define.
4214 # Use one 'alias' statement per alias you wish to define.
3811
4215
3812 # alias
4216 # alias
3813
4217
3814 #************************* end of file <ipythonrc> ************************
4218 #************************* end of file <ipythonrc> ************************
3815
4219
3816
4220
3817 ipy_user_conf.py
4221 ipy_user_conf.py
3818 ----------------
4222 ----------------
3819
4223
3820 There should be a simple template ipy_user_conf.py file in your
4224 There should be a simple template ipy_user_conf.py file in your
3821 ~/.ipython directory. It is a plain python module that is imported
4225 ~/.ipython directory. It is a plain python module that is imported
3822 during IPython startup, so you can do pretty much what you want there
4226 during IPython startup, so you can do pretty much what you want there
3823 - import modules, configure extensions, change options, define magic
4227 - import modules, configure extensions, change options, define magic
3824 commands, put variables and functions in the IPython namespace,
4228 commands, put variables and functions in the IPython namespace,
3825 etc. You use the IPython extension api object, acquired by
4229 etc. You use the IPython extension api object, acquired by
3826 IPython.ipapi.get() and documented in the "IPython extension API"
4230 IPython.ipapi.get() and documented in the "IPython extension API"
3827 chapter, to interact with IPython. A sample ipy_user_conf.py is listed
4231 chapter, to interact with IPython. A sample ipy_user_conf.py is listed
3828 below for reference::
4232 below for reference::
3829
4233
3830 # Most of your config files and extensions will probably start
4234 # Most of your config files and extensions will probably start
3831 # with this import
4235 # with this import
3832
4236
3833 import IPython.ipapi
4237 import IPython.ipapi
3834 ip = IPython.ipapi.get()
4238 ip = IPython.ipapi.get()
3835
4239
3836 # You probably want to uncomment this if you did %upgrade -nolegacy
4240 # You probably want to uncomment this if you did %upgrade -nolegacy
3837 # import ipy_defaults
4241 # import ipy_defaults
3838
4242
3839 import os
4243 import os
3840
4244
3841 def main():
4245 def main():
3842
4246
3843 #ip.dbg.debugmode = True
4247 #ip.dbg.debugmode = True
3844 ip.dbg.debug_stack()
4248 ip.dbg.debug_stack()
3845
4249
3846 # uncomment if you want to get ipython -p sh behaviour
4250 # uncomment if you want to get ipython -p sh behaviour
3847 # without having to use command line switches
4251 # without having to use command line switches
3848 import ipy_profile_sh
4252 import ipy_profile_sh
3849 import jobctrl
4253 import jobctrl
3850
4254
3851 # Configure your favourite editor?
4255 # Configure your favourite editor?
3852 # Good idea e.g. for %edit os.path.isfile
4256 # Good idea e.g. for %edit os.path.isfile
3853
4257
3854 #import ipy_editors
4258 #import ipy_editors
3855
4259
3856 # Choose one of these:
4260 # Choose one of these:
3857
4261
3858 #ipy_editors.scite()
4262 #ipy_editors.scite()
3859 #ipy_editors.scite('c:/opt/scite/scite.exe')
4263 #ipy_editors.scite('c:/opt/scite/scite.exe')
3860 #ipy_editors.komodo()
4264 #ipy_editors.komodo()
3861 #ipy_editors.idle()
4265 #ipy_editors.idle()
3862 # ... or many others, try 'ipy_editors??' after import to see them
4266 # ... or many others, try 'ipy_editors??' after import to see them
3863
4267
3864 # Or roll your own:
4268 # Or roll your own:
3865 #ipy_editors.install_editor("c:/opt/jed +$line $file")
4269 #ipy_editors.install_editor("c:/opt/jed +$line $file")
3866
4270
3867
4271
3868 o = ip.options
4272 o = ip.options
3869 # An example on how to set options
4273 # An example on how to set options
3870 #o.autocall = 1
4274 #o.autocall = 1
3871 o.system_verbose = 0
4275 o.system_verbose = 0
3872
4276
3873 #import_all("os sys")
4277 #import_all("os sys")
3874 #execf('~/_ipython/ns.py')
4278 #execf('~/_ipython/ns.py')
3875
4279
3876
4280
3877 # -- prompt
4281 # -- prompt
3878 # A different, more compact set of prompts from the default ones, that
4282 # A different, more compact set of prompts from the default ones, that
3879 # always show your current location in the filesystem:
4283 # always show your current location in the filesystem:
3880
4284
3881 #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
4285 #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
3882 #o.prompt_in2 = r'.\D: '
4286 #o.prompt_in2 = r'.\D: '
3883 #o.prompt_out = r'[\#] '
4287 #o.prompt_out = r'[\#] '
3884
4288
3885 # Try one of these color settings if you can't read the text easily
4289 # Try one of these color settings if you can't read the text easily
3886 # autoexec is a list of IPython commands to execute on startup
4290 # autoexec is a list of IPython commands to execute on startup
3887 #o.autoexec.append('%colors LightBG')
4291 #o.autoexec.append('%colors LightBG')
3888 #o.autoexec.append('%colors NoColor')
4292 #o.autoexec.append('%colors NoColor')
3889 o.autoexec.append('%colors Linux')
4293 o.autoexec.append('%colors Linux')
3890
4294
3891
4295
3892 # some config helper functions you can use
4296 # some config helper functions you can use
3893 def import_all(modules):
4297 def import_all(modules):
3894 """ Usage: import_all("os sys") """
4298 """ Usage: import_all("os sys") """
3895 for m in modules.split():
4299 for m in modules.split():
3896 ip.ex("from %s import *" % m)
4300 ip.ex("from %s import *" % m)
3897
4301
3898 def execf(fname):
4302 def execf(fname):
3899 """ Execute a file in user namespace """
4303 """ Execute a file in user namespace """
3900 ip.ex('execfile("%s")' % os.path.expanduser(fname))
4304 ip.ex('execfile("%s")' % os.path.expanduser(fname))
3901
4305
3902 main()
4306 main()
3903
4307
3904
4308 .. _Prompts:
3905
4309
3906 Fine-tuning your prompt
4310 Fine-tuning your prompt
3907 -----------------------
4311 -----------------------
3908
4312
3909 IPython's prompts can be customized using a syntax similar to that of
4313 IPython's prompts can be customized using a syntax similar to that of
3910 the bash shell. Many of bash's escapes are supported, as well as a few
4314 the bash shell. Many of bash's escapes are supported, as well as a few
3911 additional ones. We list them below::
4315 additional ones. We list them below::
3912
4316
3913 \#
4317 \#
3914 the prompt/history count number. This escape is automatically
4318 the prompt/history count number. This escape is automatically
3915 wrapped in the coloring codes for the currently active color scheme.
4319 wrapped in the coloring codes for the currently active color scheme.
3916 \N
4320 \N
3917 the 'naked' prompt/history count number: this is just the number
4321 the 'naked' prompt/history count number: this is just the number
3918 itself, without any coloring applied to it. This lets you produce
4322 itself, without any coloring applied to it. This lets you produce
3919 numbered prompts with your own colors.
4323 numbered prompts with your own colors.
3920 \D
4324 \D
3921 the prompt/history count, with the actual digits replaced by dots.
4325 the prompt/history count, with the actual digits replaced by dots.
3922 Used mainly in continuation prompts (prompt_in2)
4326 Used mainly in continuation prompts (prompt_in2)
3923 \w
4327 \w
3924 the current working directory
4328 the current working directory
3925 \W
4329 \W
3926 the basename of current working directory
4330 the basename of current working directory
3927 \Xn
4331 \Xn
3928 where $n=0\ldots5.$ The current working directory, with $HOME
4332 where $n=0\ldots5.$ The current working directory, with $HOME
3929 replaced by ~, and filtered out to contain only $n$ path elements
4333 replaced by ~, and filtered out to contain only $n$ path elements
3930 \Yn
4334 \Yn
3931 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
4335 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
3932 is similar to the behavior of the %cn escapes in tcsh)
4336 is similar to the behavior of the %cn escapes in tcsh)
3933 \u
4337 \u
3934 the username of the current user
4338 the username of the current user
3935 \$
4339 \$
3936 if the effective UID is 0, a #, otherwise a $
4340 if the effective UID is 0, a #, otherwise a $
3937 \h
4341 \h
3938 the hostname up to the first '.'
4342 the hostname up to the first '.'
3939 \H
4343 \H
3940 the hostname
4344 the hostname
3941 \n
4345 \n
3942 a newline
4346 a newline
3943 \r
4347 \r
3944 a carriage return
4348 a carriage return
3945 \v
4349 \v
3946 IPython version string
4350 IPython version string
3947
4351
3948 In addition to these, ANSI color escapes can be insterted into the
4352 In addition to these, ANSI color escapes can be insterted into the
3949 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
4353 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
3950 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
4354 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
3951 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
4355 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
3952 Yellow.
4356 Yellow.
3953
4357
3954 Finally, IPython supports the evaluation of arbitrary expressions in
4358 Finally, IPython supports the evaluation of arbitrary expressions in
3955 your prompt string. The prompt strings are evaluated through the syntax
4359 your prompt string. The prompt strings are evaluated through the syntax
3956 of PEP 215, but basically you can use $x.y to expand the value of x.y,
4360 of PEP 215, but basically you can use $x.y to expand the value of x.y,
3957 and for more complicated expressions you can use braces: ${foo()+x} will
4361 and for more complicated expressions you can use braces: ${foo()+x} will
3958 call function foo and add to it the value of x, before putting the
4362 call function foo and add to it the value of x, before putting the
3959 result into your prompt. For example, using
4363 result into your prompt. For example, using
3960 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
4364 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
3961 will print the result of the uptime command on each prompt (assuming the
4365 will print the result of the uptime command on each prompt (assuming the
3962 commands module has been imported in your ipythonrc file).
4366 commands module has been imported in your ipythonrc file).
3963
4367
3964
4368
3965 Prompt examples
4369 Prompt examples
3966
4370
3967 The following options in an ipythonrc file will give you IPython's
4371 The following options in an ipythonrc file will give you IPython's
3968 default prompts::
4372 default prompts::
3969
4373
3970 prompt_in1 'In [\#]:'
4374 prompt_in1 'In [\#]:'
3971 prompt_in2 ' .\D.:'
4375 prompt_in2 ' .\D.:'
3972 prompt_out 'Out[\#]:'
4376 prompt_out 'Out[\#]:'
3973
4377
3974 which look like this::
4378 which look like this::
3975
4379
3976 In [1]: 1+2
4380 In [1]: 1+2
3977 Out[1]: 3
4381 Out[1]: 3
3978
4382
3979 In [2]: for i in (1,2,3):
4383 In [2]: for i in (1,2,3):
3980 ...: print i,
4384 ...: print i,
3981 ...:
4385 ...:
3982 1 2 3
4386 1 2 3
3983
4387
3984 These will give you a very colorful prompt with path information::
4388 These will give you a very colorful prompt with path information::
3985
4389
3986 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
4390 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
3987 prompt_in2 ' ..\D>'
4391 prompt_in2 ' ..\D>'
3988 prompt_out '<\#>'
4392 prompt_out '<\#>'
3989
4393
3990 which look like this::
4394 which look like this::
3991
4395
3992 fperez[~/ipython]1> 1+2
4396 fperez[~/ipython]1> 1+2
3993 <1> 3
4397 <1> 3
3994 fperez[~/ipython]2> for i in (1,2,3):
4398 fperez[~/ipython]2> for i in (1,2,3):
3995 ...> print i,
4399 ...> print i,
3996 ...>
4400 ...>
3997 1 2 3
4401 1 2 3
3998
4402
3999
4403
4404 .. _Profiles:
4000
4405
4001 IPython profiles
4406 IPython profiles
4002 ----------------
4407 ----------------
4003
4408
4004 As we already mentioned, IPython supports the -profile command-line
4409 As we already mentioned, IPython supports the -profile command-line
4005 option (see sec. 5.2 <node5.html#sec:cmd-line-opts>). A profile is
4410 option (see sec. `command line options`_). A profile is nothing more
4006 nothing more than a particular configuration file like your basic
4411 than a particular configuration file like your basic ipythonrc one,
4007 ipythonrc one, but with particular customizations for a specific
4412 but with particular customizations for a specific purpose. When you
4008 purpose. When you start IPython with 'ipython -profile <name>', it
4413 start IPython with 'ipython -profile <name>', it assumes that in your
4009 assumes that in your IPYTHONDIR there is a file called ipythonrc-<name>,
4414 IPYTHONDIR there is a file called ipythonrc-<name> or
4010 and loads it instead of the normal ipythonrc.
4415 ipy_profile_<name>.py, and loads it instead of the normal ipythonrc.
4011
4416
4012 This system allows you to maintain multiple configurations which load
4417 This system allows you to maintain multiple configurations which load
4013 modules, set options, define functions, etc. suitable for different
4418 modules, set options, define functions, etc. suitable for different
4014 tasks and activate them in a very simple manner. In order to avoid
4419 tasks and activate them in a very simple manner. In order to avoid
4015 having to repeat all of your basic options (common things that don't
4420 having to repeat all of your basic options (common things that don't
4016 change such as your color preferences, for example), any profile can
4421 change such as your color preferences, for example), any profile can
4017 include another configuration file. The most common way to use profiles
4422 include another configuration file. The most common way to use profiles
4018 is then to have each one include your basic ipythonrc file as a starting
4423 is then to have each one include your basic ipythonrc file as a starting
4019 point, and then add further customizations.
4424 point, and then add further customizations.
4020
4425
4021 In sections 11 <node11.html#sec:syntax-extensions> and 16
4022 <node16.html#sec:Gnuplot> we discuss some particular profiles which come
4023 as part of the standard IPython distribution. You may also look in your
4024 IPYTHONDIR directory, any file whose name begins with ipythonrc- is a
4025 profile. You can use those as examples for further customizations to
4026 suit your own needs.
4027
4028 IPython as your default Python environment
4426 IPython as your default Python environment
4029 ==========================================
4427 ==========================================
4030
4428
4031 Python honors the environment variable PYTHONSTARTUP and will execute at
4429 Python honors the environment variable PYTHONSTARTUP and will execute at
4032 startup the file referenced by this variable. If you put at the end of
4430 startup the file referenced by this variable. If you put at the end of
4033 this file the following two lines of code::
4431 this file the following two lines of code::
4034
4432
4035 import IPython
4433 import IPython
4036 IPython.Shell.IPShell().mainloop(sys_exit=1)
4434 IPython.Shell.IPShell().mainloop(sys_exit=1)
4037
4435
4038 then IPython will be your working environment anytime you start Python.
4436 then IPython will be your working environment anytime you start Python.
4039 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
4437 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
4040 it finishes, otherwise you'll be back at the normal Python '>>>'
4438 it finishes, otherwise you'll be back at the normal Python '>>>'
4041 prompt^4 <footnode.html#foot2368>.
4439 prompt.
4042
4440
4043 This is probably useful to developers who manage multiple Python
4441 This is probably useful to developers who manage multiple Python
4044 versions and don't want to have correspondingly multiple IPython
4442 versions and don't want to have correspondingly multiple IPython
4045 versions. Note that in this mode, there is no way to pass IPython any
4443 versions. Note that in this mode, there is no way to pass IPython any
4046 command-line options, as those are trapped first by Python itself.
4444 command-line options, as those are trapped first by Python itself.
4047
4445
4446 .. _Embedding:
4447
4048 Embedding IPython
4448 Embedding IPython
4049 =================
4449 =================
4050
4450
4051 It is possible to start an IPython instance inside your own Python
4451 It is possible to start an IPython instance inside your own Python
4052 programs. This allows you to evaluate dynamically the state of your
4452 programs. This allows you to evaluate dynamically the state of your
4053 code, operate with your variables, analyze them, etc. Note however that
4453 code, operate with your variables, analyze them, etc. Note however that
4054 any changes you make to values while in the shell do not propagate back
4454 any changes you make to values while in the shell do not propagate back
4055 to the running code, so it is safe to modify your values because you
4455 to the running code, so it is safe to modify your values because you
4056 won't break your code in bizarre ways by doing so.
4456 won't break your code in bizarre ways by doing so.
4057
4457
4058 This feature allows you to easily have a fully functional python
4458 This feature allows you to easily have a fully functional python
4059 environment for doing object introspection anywhere in your code with a
4459 environment for doing object introspection anywhere in your code with a
4060 simple function call. In some cases a simple print statement is enough,
4460 simple function call. In some cases a simple print statement is enough,
4061 but if you need to do more detailed analysis of a code fragment this
4461 but if you need to do more detailed analysis of a code fragment this
4062 feature can be very valuable.
4462 feature can be very valuable.
4063
4463
4064 It can also be useful in scientific computing situations where it is
4464 It can also be useful in scientific computing situations where it is
4065 common to need to do some automatic, computationally intensive part and
4465 common to need to do some automatic, computationally intensive part and
4066 then stop to look at data, plots, etc^5 <footnode.html#foot3206>.
4466 then stop to look at data, plots, etc.
4067 Opening an IPython instance will give you full access to your data and
4467 Opening an IPython instance will give you full access to your data and
4068 functions, and you can resume program execution once you are done with
4468 functions, and you can resume program execution once you are done with
4069 the interactive part (perhaps to stop again later, as many times as
4469 the interactive part (perhaps to stop again later, as many times as
4070 needed).
4470 needed).
4071
4471
4072 The following code snippet is the bare minimum you need to include in
4472 The following code snippet is the bare minimum you need to include in
4073 your Python programs for this to work (detailed examples follow later)::
4473 your Python programs for this to work (detailed examples follow later)::
4074
4474
4075 from IPython.Shell import IPShellEmbed
4475 from IPython.Shell import IPShellEmbed
4076
4476
4077 ipshell = IPShellEmbed()
4477 ipshell = IPShellEmbed()
4078
4478
4079 ipshell() # this call anywhere in your program will start IPython
4479 ipshell() # this call anywhere in your program will start IPython
4080
4480
4081 You can run embedded instances even in code which is itself being run at
4481 You can run embedded instances even in code which is itself being run at
4082 the IPython interactive prompt with '%run <filename>'. Since it's easy
4482 the IPython interactive prompt with '%run <filename>'. Since it's easy
4083 to get lost as to where you are (in your top-level IPython or in your
4483 to get lost as to where you are (in your top-level IPython or in your
4084 embedded one), it's a good idea in such cases to set the in/out prompts
4484 embedded one), it's a good idea in such cases to set the in/out prompts
4085 to something different for the embedded instances. The code examples
4485 to something different for the embedded instances. The code examples
4086 below illustrate this.
4486 below illustrate this.
4087
4487
4088 You can also have multiple IPython instances in your program and open
4488 You can also have multiple IPython instances in your program and open
4089 them separately, for example with different options for data
4489 them separately, for example with different options for data
4090 presentation. If you close and open the same instance multiple times,
4490 presentation. If you close and open the same instance multiple times,
4091 its prompt counters simply continue from each execution to the next.
4491 its prompt counters simply continue from each execution to the next.
4092
4492
4093 Please look at the docstrings in the Shell.py module for more details on
4493 Please look at the docstrings in the Shell.py module for more details on
4094 the use of this system.
4494 the use of this system.
4095
4495
4096 The following sample file illustrating how to use the embedding
4496 The following sample file illustrating how to use the embedding
4097 functionality is provided in the examples directory as example-embed.py.
4497 functionality is provided in the examples directory as example-embed.py.
4098 It should be fairly self-explanatory::
4498 It should be fairly self-explanatory::
4099
4499
4100
4500
4101 #!/usr/bin/env python
4501 #!/usr/bin/env python
4102
4502
4103 """An example of how to embed an IPython shell into a running program.
4503 """An example of how to embed an IPython shell into a running program.
4104
4504
4105 Please see the documentation in the IPython.Shell module for more details.
4505 Please see the documentation in the IPython.Shell module for more details.
4106
4506
4107 The accompanying file example-embed-short.py has quick code fragments for
4507 The accompanying file example-embed-short.py has quick code fragments for
4108 embedding which you can cut and paste in your code once you understand how
4508 embedding which you can cut and paste in your code once you understand how
4109 things work.
4509 things work.
4110
4510
4111 The code in this file is deliberately extra-verbose, meant for learning."""
4511 The code in this file is deliberately extra-verbose, meant for learning."""
4112
4512
4113 # The basics to get you going:
4513 # The basics to get you going:
4114
4514
4115 # IPython sets the __IPYTHON__ variable so you can know if you have nested
4515 # IPython sets the __IPYTHON__ variable so you can know if you have nested
4116 # copies running.
4516 # copies running.
4117
4517
4118 # Try running this code both at the command line and from inside IPython (with
4518 # Try running this code both at the command line and from inside IPython (with
4119 # %run example-embed.py)
4519 # %run example-embed.py)
4120 try:
4520 try:
4121 __IPYTHON__
4521 __IPYTHON__
4122 except NameError:
4522 except NameError:
4123 nested = 0
4523 nested = 0
4124 args = ['']
4524 args = ['']
4125 else:
4525 else:
4126 print "Running nested copies of IPython."
4526 print "Running nested copies of IPython."
4127 print "The prompts for the nested copy have been modified"
4527 print "The prompts for the nested copy have been modified"
4128 nested = 1
4528 nested = 1
4129 # what the embedded instance will see as sys.argv:
4529 # what the embedded instance will see as sys.argv:
4130 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
4530 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
4131 '-po','Out<\\#>: ','-nosep']
4531 '-po','Out<\\#>: ','-nosep']
4132
4532
4133 # First import the embeddable shell class
4533 # First import the embeddable shell class
4134 from IPython.Shell import IPShellEmbed
4534 from IPython.Shell import IPShellEmbed
4135
4535
4136 # Now create an instance of the embeddable shell. The first argument is a
4536 # Now create an instance of the embeddable shell. The first argument is a
4137 # string with options exactly as you would type them if you were starting
4537 # string with options exactly as you would type them if you were starting
4138 # IPython at the system command line. Any parameters you want to define for
4538 # IPython at the system command line. Any parameters you want to define for
4139 # configuration can thus be specified here.
4539 # configuration can thus be specified here.
4140 ipshell = IPShellEmbed(args,
4540 ipshell = IPShellEmbed(args,
4141 banner = 'Dropping into IPython',
4541 banner = 'Dropping into IPython',
4142 exit_msg = 'Leaving Interpreter, back to program.')
4542 exit_msg = 'Leaving Interpreter, back to program.')
4143
4543
4144 # Make a second instance, you can have as many as you want.
4544 # Make a second instance, you can have as many as you want.
4145 if nested:
4545 if nested:
4146 args[1] = 'In2<\\#>'
4546 args[1] = 'In2<\\#>'
4147 else:
4547 else:
4148 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
4548 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
4149 '-po','Out<\\#>: ','-nosep']
4549 '-po','Out<\\#>: ','-nosep']
4150 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
4550 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
4151
4551
4152 print '\nHello. This is printed from the main controller program.\n'
4552 print '\nHello. This is printed from the main controller program.\n'
4153
4553
4154 # You can then call ipshell() anywhere you need it (with an optional
4554 # You can then call ipshell() anywhere you need it (with an optional
4155 # message):
4555 # message):
4156 ipshell('***Called from top level. '
4556 ipshell('***Called from top level. '
4157 'Hit Ctrl-D to exit interpreter and continue program.\n'
4557 'Hit Ctrl-D to exit interpreter and continue program.\n'
4158 'Note that if you use %kill_embedded, you can fully deactivate\n'
4558 'Note that if you use %kill_embedded, you can fully deactivate\n'
4159 'This embedded instance so it will never turn on again')
4559 'This embedded instance so it will never turn on again')
4160
4560
4161 print '\nBack in caller program, moving along...\n'
4561 print '\nBack in caller program, moving along...\n'
4162
4562
4163 #---------------------------------------------------------------------------
4563 #---------------------------------------------------------------------------
4164 # More details:
4564 # More details:
4165
4565
4166 # IPShellEmbed instances don't print the standard system banner and
4566 # IPShellEmbed instances don't print the standard system banner and
4167 # messages. The IPython banner (which actually may contain initialization
4567 # messages. The IPython banner (which actually may contain initialization
4168 # messages) is available as <instance>.IP.BANNER in case you want it.
4568 # messages) is available as <instance>.IP.BANNER in case you want it.
4169
4569
4170 # IPShellEmbed instances print the following information everytime they
4570 # IPShellEmbed instances print the following information everytime they
4171 # start:
4571 # start:
4172
4572
4173 # - A global startup banner.
4573 # - A global startup banner.
4174
4574
4175 # - A call-specific header string, which you can use to indicate where in the
4575 # - A call-specific header string, which you can use to indicate where in the
4176 # execution flow the shell is starting.
4576 # execution flow the shell is starting.
4177
4577
4178 # They also print an exit message every time they exit.
4578 # They also print an exit message every time they exit.
4179
4579
4180 # Both the startup banner and the exit message default to None, and can be set
4580 # Both the startup banner and the exit message default to None, and can be set
4181 # either at the instance constructor or at any other time with the
4581 # either at the instance constructor or at any other time with the
4182 # set_banner() and set_exit_msg() methods.
4582 # set_banner() and set_exit_msg() methods.
4183
4583
4184 # The shell instance can be also put in 'dummy' mode globally or on a per-call
4584 # The shell instance can be also put in 'dummy' mode globally or on a per-call
4185 # basis. This gives you fine control for debugging without having to change
4585 # basis. This gives you fine control for debugging without having to change
4186 # code all over the place.
4586 # code all over the place.
4187
4587
4188 # The code below illustrates all this.
4588 # The code below illustrates all this.
4189
4589
4190
4590
4191 # This is how the global banner and exit_msg can be reset at any point
4591 # This is how the global banner and exit_msg can be reset at any point
4192 ipshell.set_banner('Entering interpreter - New Banner')
4592 ipshell.set_banner('Entering interpreter - New Banner')
4193 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
4593 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
4194
4594
4195 def foo(m):
4595 def foo(m):
4196 s = 'spam'
4596 s = 'spam'
4197 ipshell('***In foo(). Try @whos, or print s or m:')
4597 ipshell('***In foo(). Try @whos, or print s or m:')
4198 print 'foo says m = ',m
4598 print 'foo says m = ',m
4199
4599
4200 def bar(n):
4600 def bar(n):
4201 s = 'eggs'
4601 s = 'eggs'
4202 ipshell('***In bar(). Try @whos, or print s or n:')
4602 ipshell('***In bar(). Try @whos, or print s or n:')
4203 print 'bar says n = ',n
4603 print 'bar says n = ',n
4204
4604
4205 # Some calls to the above functions which will trigger IPython:
4605 # Some calls to the above functions which will trigger IPython:
4206 print 'Main program calling foo("eggs")\n'
4606 print 'Main program calling foo("eggs")\n'
4207 foo('eggs')
4607 foo('eggs')
4208
4608
4209 # The shell can be put in 'dummy' mode where calls to it silently return. This
4609 # The shell can be put in 'dummy' mode where calls to it silently return. This
4210 # allows you, for example, to globally turn off debugging for a program with a
4610 # allows you, for example, to globally turn off debugging for a program with a
4211 # single call.
4611 # single call.
4212 ipshell.set_dummy_mode(1)
4612 ipshell.set_dummy_mode(1)
4213 print '\nTrying to call IPython which is now "dummy":'
4613 print '\nTrying to call IPython which is now "dummy":'
4214 ipshell()
4614 ipshell()
4215 print 'Nothing happened...'
4615 print 'Nothing happened...'
4216 # The global 'dummy' mode can still be overridden for a single call
4616 # The global 'dummy' mode can still be overridden for a single call
4217 print '\nOverriding dummy mode manually:'
4617 print '\nOverriding dummy mode manually:'
4218 ipshell(dummy=0)
4618 ipshell(dummy=0)
4219
4619
4220 # Reactivate the IPython shell
4620 # Reactivate the IPython shell
4221 ipshell.set_dummy_mode(0)
4621 ipshell.set_dummy_mode(0)
4222
4622
4223 print 'You can even have multiple embedded instances:'
4623 print 'You can even have multiple embedded instances:'
4224 ipshell2()
4624 ipshell2()
4225
4625
4226 print '\nMain program calling bar("spam")\n'
4626 print '\nMain program calling bar("spam")\n'
4227 bar('spam')
4627 bar('spam')
4228
4628
4229 print 'Main program finished. Bye!'
4629 print 'Main program finished. Bye!'
4230
4630
4231 #********************** End of file <example-embed.py> ***********************
4631 #********************** End of file <example-embed.py> ***********************
4232
4632
4233 Once you understand how the system functions, you can use the following
4633 Once you understand how the system functions, you can use the following
4234 code fragments in your programs which are ready for cut and paste::
4634 code fragments in your programs which are ready for cut and paste::
4235
4635
4236
4636
4237 """Quick code snippets for embedding IPython into other programs.
4637 """Quick code snippets for embedding IPython into other programs.
4238
4638
4239 See example-embed.py for full details, this file has the bare minimum code for
4639 See example-embed.py for full details, this file has the bare minimum code for
4240 cut and paste use once you understand how to use the system."""
4640 cut and paste use once you understand how to use the system."""
4241
4641
4242 #---------------------------------------------------------------------------
4642 #---------------------------------------------------------------------------
4243 # This code loads IPython but modifies a few things if it detects it's running
4643 # This code loads IPython but modifies a few things if it detects it's running
4244 # embedded in another IPython session (helps avoid confusion)
4644 # embedded in another IPython session (helps avoid confusion)
4245
4645
4246 try:
4646 try:
4247 __IPYTHON__
4647 __IPYTHON__
4248 except NameError:
4648 except NameError:
4249 argv = ['']
4649 argv = ['']
4250 banner = exit_msg = ''
4650 banner = exit_msg = ''
4251 else:
4651 else:
4252 # Command-line options for IPython (a list like sys.argv)
4652 # Command-line options for IPython (a list like sys.argv)
4253 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
4653 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
4254 banner = '*** Nested interpreter ***'
4654 banner = '*** Nested interpreter ***'
4255 exit_msg = '*** Back in main IPython ***'
4655 exit_msg = '*** Back in main IPython ***'
4256
4656
4257 # First import the embeddable shell class
4657 # First import the embeddable shell class
4258 from IPython.Shell import IPShellEmbed
4658 from IPython.Shell import IPShellEmbed
4259 # Now create the IPython shell instance. Put ipshell() anywhere in your code
4659 # Now create the IPython shell instance. Put ipshell() anywhere in your code
4260 # where you want it to open.
4660 # where you want it to open.
4261 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
4661 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
4262
4662
4263 #---------------------------------------------------------------------------
4663 #---------------------------------------------------------------------------
4264 # This code will load an embeddable IPython shell always with no changes for
4664 # This code will load an embeddable IPython shell always with no changes for
4265 # nested embededings.
4665 # nested embededings.
4266
4666
4267 from IPython.Shell import IPShellEmbed
4667 from IPython.Shell import IPShellEmbed
4268 ipshell = IPShellEmbed()
4668 ipshell = IPShellEmbed()
4269 # Now ipshell() will open IPython anywhere in the code.
4669 # Now ipshell() will open IPython anywhere in the code.
4270
4670
4271 #---------------------------------------------------------------------------
4671 #---------------------------------------------------------------------------
4272 # This code loads an embeddable shell only if NOT running inside
4672 # This code loads an embeddable shell only if NOT running inside
4273 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
4673 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
4274 # dummy function.
4674 # dummy function.
4275
4675
4276 try:
4676 try:
4277 __IPYTHON__
4677 __IPYTHON__
4278 except NameError:
4678 except NameError:
4279 from IPython.Shell import IPShellEmbed
4679 from IPython.Shell import IPShellEmbed
4280 ipshell = IPShellEmbed()
4680 ipshell = IPShellEmbed()
4281 # Now ipshell() will open IPython anywhere in the code
4681 # Now ipshell() will open IPython anywhere in the code
4282 else:
4682 else:
4283 # Define a dummy ipshell() so the same code doesn't crash inside an
4683 # Define a dummy ipshell() so the same code doesn't crash inside an
4284 # interactive IPython
4684 # interactive IPython
4285 def ipshell(): pass
4685 def ipshell(): pass
4286
4686
4287 #******************* End of file <example-embed-short.py> ********************
4687 #******************* End of file <example-embed-short.py> ********************
4288
4688
4289 Using the Python debugger (pdb)
4689 Using the Python debugger (pdb)
4290 ===============================
4690 ===============================
4291
4691
4292 Running entire programs via pdb
4692 Running entire programs via pdb
4293 -------------------------------
4693 -------------------------------
4294
4694
4295 pdb, the Python debugger, is a powerful interactive debugger which
4695 pdb, the Python debugger, is a powerful interactive debugger which
4296 allows you to step through code, set breakpoints, watch variables, etc.
4696 allows you to step through code, set breakpoints, watch variables,
4297 IPython makes it very easy to start any script under the control of pdb,
4697 etc. IPython makes it very easy to start any script under the control
4298 regardless of whether you have wrapped it into a 'main()' function or
4698 of pdb, regardless of whether you have wrapped it into a 'main()'
4299 not. For this, simply type '%run -d myscript' at an IPython prompt. See
4699 function or not. For this, simply type '%run -d myscript' at an
4300 the %run command's documentation (via '%run?' or in Sec. 6.2
4700 IPython prompt. See the %run command's documentation (via '%run?' or
4301 <node6.html#sec:magic>) for more details, including how to control where
4701 in Sec. magic_ for more details, including how to control where pdb
4302 pdb will stop execution first.
4702 will stop execution first.
4303
4703
4304 For more information on the use of the pdb debugger, read the included
4704 For more information on the use of the pdb debugger, read the included
4305 pdb.doc file (part of the standard Python distribution). On a stock
4705 pdb.doc file (part of the standard Python distribution). On a stock
4306 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
4706 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
4307 easiest way to read it is by using the help() function of the pdb module
4707 easiest way to read it is by using the help() function of the pdb module
4308 as follows (in an IPython prompt):
4708 as follows (in an IPython prompt):
4309
4709
4310 In [1]: import pdb
4710 In [1]: import pdb
4311 In [2]: pdb.help()
4711 In [2]: pdb.help()
4312
4712
4313 This will load the pdb.doc document in a file viewer for you automatically.
4713 This will load the pdb.doc document in a file viewer for you automatically.
4314
4714
4315
4715
4316 Automatic invocation of pdb on exceptions
4716 Automatic invocation of pdb on exceptions
4317 -----------------------------------------
4717 -----------------------------------------
4318
4718
4319 IPython, if started with the -pdb option (or if the option is set in
4719 IPython, if started with the -pdb option (or if the option is set in
4320 your rc file) can call the Python pdb debugger every time your code
4720 your rc file) can call the Python pdb debugger every time your code
4321 triggers an uncaught exception^6 <footnode.html#foot2403>. This feature
4721 triggers an uncaught exception. This feature
4322 can also be toggled at any time with the %pdb magic command. This can be
4722 can also be toggled at any time with the %pdb magic command. This can be
4323 extremely useful in order to find the origin of subtle bugs, because pdb
4723 extremely useful in order to find the origin of subtle bugs, because pdb
4324 opens up at the point in your code which triggered the exception, and
4724 opens up at the point in your code which triggered the exception, and
4325 while your program is at this point 'dead', all the data is still
4725 while your program is at this point 'dead', all the data is still
4326 available and you can walk up and down the stack frame and understand
4726 available and you can walk up and down the stack frame and understand
4327 the origin of the problem.
4727 the origin of the problem.
4328
4728
4329 Furthermore, you can use these debugging facilities both with the
4729 Furthermore, you can use these debugging facilities both with the
4330 embedded IPython mode and without IPython at all. For an embedded shell
4730 embedded IPython mode and without IPython at all. For an embedded shell
4331 (see sec. 9 <node9.html#sec:embed>), simply call the constructor with
4731 (see sec. Embedding_), simply call the constructor with
4332 '-pdb' in the argument string and automatically pdb will be called if an
4732 '-pdb' in the argument string and automatically pdb will be called if an
4333 uncaught exception is triggered by your code.
4733 uncaught exception is triggered by your code.
4334
4734
4335 For stand-alone use of the feature in your programs which do not use
4735 For stand-alone use of the feature in your programs which do not use
4336 IPython at all, put the following lines toward the top of your 'main'
4736 IPython at all, put the following lines toward the top of your 'main'
4337 routine::
4737 routine::
4338
4738
4339 import sys,IPython.ultraTB
4739 import sys,IPython.ultraTB
4340 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
4740 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
4341 color_scheme='Linux', call_pdb=1)
4741 color_scheme='Linux', call_pdb=1)
4342
4742
4343 The mode keyword can be either 'Verbose' or 'Plain', giving either very
4743 The mode keyword can be either 'Verbose' or 'Plain', giving either very
4344 detailed or normal tracebacks respectively. The color_scheme keyword can
4744 detailed or normal tracebacks respectively. The color_scheme keyword can
4345 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
4745 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
4346 options which can be set in IPython with -colors and -xmode.
4746 options which can be set in IPython with -colors and -xmode.
4347
4747
4348 This will give any of your programs detailed, colored tracebacks with
4748 This will give any of your programs detailed, colored tracebacks with
4349 automatic invocation of pdb.
4749 automatic invocation of pdb.
4350
4750
4351
4751
4352 Extensions for syntax processing
4752 Extensions for syntax processing
4353 ================================
4753 ================================
4354
4754
4355 This isn't for the faint of heart, because the potential for breaking
4755 This isn't for the faint of heart, because the potential for breaking
4356 things is quite high. But it can be a very powerful and useful feature.
4756 things is quite high. But it can be a very powerful and useful feature.
4357 In a nutshell, you can redefine the way IPython processes the user input
4757 In a nutshell, you can redefine the way IPython processes the user input
4358 line to accept new, special extensions to the syntax without needing to
4758 line to accept new, special extensions to the syntax without needing to
4359 change any of IPython's own code.
4759 change any of IPython's own code.
4360
4760
4361 In the IPython/Extensions directory you will find some examples
4761 In the IPython/Extensions directory you will find some examples
4362 supplied, which we will briefly describe now. These can be used 'as is'
4762 supplied, which we will briefly describe now. These can be used 'as is'
4363 (and both provide very useful functionality), or you can use them as a
4763 (and both provide very useful functionality), or you can use them as a
4364 starting point for writing your own extensions.
4764 starting point for writing your own extensions.
4365
4765
4366
4766
4367 Pasting of code starting with '>>> ' or '... '
4767 Pasting of code starting with '>>> ' or '... '
4368 ----------------------------------------------
4768 ----------------------------------------------
4369
4769
4370 In the python tutorial it is common to find code examples which have
4770 In the python tutorial it is common to find code examples which have
4371 been taken from real python sessions. The problem with those is that all
4771 been taken from real python sessions. The problem with those is that all
4372 the lines begin with either '>>> ' or '... ', which makes it impossible
4772 the lines begin with either '>>> ' or '... ', which makes it impossible
4373 to paste them all at once. One must instead do a line by line manual
4773 to paste them all at once. One must instead do a line by line manual
4374 copying, carefully removing the leading extraneous characters.
4774 copying, carefully removing the leading extraneous characters.
4375
4775
4376 This extension identifies those starting characters and removes them
4776 This extension identifies those starting characters and removes them
4377 from the input automatically, so that one can paste multi-line examples
4777 from the input automatically, so that one can paste multi-line examples
4378 directly into IPython, saving a lot of time. Please look at the file
4778 directly into IPython, saving a lot of time. Please look at the file
4379 InterpreterPasteInput.py in the IPython/Extensions directory for details
4779 InterpreterPasteInput.py in the IPython/Extensions directory for details
4380 on how this is done.
4780 on how this is done.
4381
4781
4382 IPython comes with a special profile enabling this feature, called
4782 IPython comes with a special profile enabling this feature, called
4383 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
4783 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
4384 will be available. In a normal IPython session you can activate the
4784 will be available. In a normal IPython session you can activate the
4385 feature by importing the corresponding module with:
4785 feature by importing the corresponding module with:
4386 In [1]: import IPython.Extensions.InterpreterPasteInput
4786 In [1]: import IPython.Extensions.InterpreterPasteInput
4387
4787
4388 The following is a 'screenshot' of how things work when this extension
4788 The following is a 'screenshot' of how things work when this extension
4389 is on, copying an example from the standard tutorial::
4789 is on, copying an example from the standard tutorial::
4390
4790
4391 IPython profile: tutorial
4791 IPython profile: tutorial
4392
4792
4393 *** Pasting of code with ">>>" or "..." has been enabled.
4793 *** Pasting of code with ">>>" or "..." has been enabled.
4394
4794
4395 In [1]: >>> def fib2(n): # return Fibonacci series up to n
4795 In [1]: >>> def fib2(n): # return Fibonacci series up to n
4396 ...: ... """Return a list containing the Fibonacci series up to
4796 ...: ... """Return a list containing the Fibonacci series up to
4397 n."""
4797 n."""
4398 ...: ... result = []
4798 ...: ... result = []
4399 ...: ... a, b = 0, 1
4799 ...: ... a, b = 0, 1
4400 ...: ... while b < n:
4800 ...: ... while b < n:
4401 ...: ... result.append(b) # see below
4801 ...: ... result.append(b) # see below
4402 ...: ... a, b = b, a+b
4802 ...: ... a, b = b, a+b
4403 ...: ... return result
4803 ...: ... return result
4404 ...:
4804 ...:
4405
4805
4406 In [2]: fib2(10)
4806 In [2]: fib2(10)
4407 Out[2]: [1, 1, 2, 3, 5, 8]
4807 Out[2]: [1, 1, 2, 3, 5, 8]
4408
4808
4409 Note that as currently written, this extension does not recognize
4809 Note that as currently written, this extension does not recognize
4410 IPython's prompts for pasting. Those are more complicated, since the
4810 IPython's prompts for pasting. Those are more complicated, since the
4411 user can change them very easily, they involve numbers and can vary in
4811 user can change them very easily, they involve numbers and can vary in
4412 length. One could however extract all the relevant information from the
4812 length. One could however extract all the relevant information from the
4413 IPython instance and build an appropriate regular expression. This is
4813 IPython instance and build an appropriate regular expression. This is
4414 left as an exercise for the reader.
4814 left as an exercise for the reader.
4415
4815
4416
4816
4417 Input of physical quantities with units
4817 Input of physical quantities with units
4418 ---------------------------------------
4818 ---------------------------------------
4419
4819
4420 The module PhysicalQInput allows a simplified form of input for physical
4820 The module PhysicalQInput allows a simplified form of input for physical
4421 quantities with units. This file is meant to be used in conjunction with
4821 quantities with units. This file is meant to be used in conjunction with
4422 the PhysicalQInteractive module (in the same directory) and
4822 the PhysicalQInteractive module (in the same directory) and
4423 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
4823 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
4424 (http://dirac.cnrs-orleans.fr/ScientificPython/).
4824 (http://dirac.cnrs-orleans.fr/ScientificPython/).
4425
4825
4426 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
4826 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
4427 but these must be declared as instances of a class. For example, to
4827 but these must be declared as instances of a class. For example, to
4428 define v as a velocity of 3 m/s, normally you would write::
4828 define v as a velocity of 3 m/s, normally you would write::
4429
4829
4430 In [1]: v = PhysicalQuantity(3,'m/s')
4830 In [1]: v = PhysicalQuantity(3,'m/s')
4431
4831
4432 Using the PhysicalQ_Input extension this can be input instead as:
4832 Using the PhysicalQ_Input extension this can be input instead as:
4433 In [1]: v = 3 m/s
4833 In [1]: v = 3 m/s
4434 which is much more convenient for interactive use (even though it is
4834 which is much more convenient for interactive use (even though it is
4435 blatantly invalid Python syntax).
4835 blatantly invalid Python syntax).
4436
4836
4437 The physics profile supplied with IPython (enabled via 'ipython -p
4837 The physics profile supplied with IPython (enabled via 'ipython -p
4438 physics') uses these extensions, which you can also activate with:
4838 physics') uses these extensions, which you can also activate with:
4439
4839
4440 from math import * # math MUST be imported BEFORE PhysicalQInteractive
4840 from math import * # math MUST be imported BEFORE PhysicalQInteractive
4441 from IPython.Extensions.PhysicalQInteractive import *
4841 from IPython.Extensions.PhysicalQInteractive import *
4442 import IPython.Extensions.PhysicalQInput
4842 import IPython.Extensions.PhysicalQInput
4443
4843
4444
4844
4445 IPython as a system shell - the 'Sh' profile
4845 IPython as a system shell - the 'Sh' profile
4446 ============================================
4846 ============================================
4447
4847
4448 The 'sh' profile optimizes IPython for system shell usage. Apart from
4848 The 'sh' profile optimizes IPython for system shell usage. Apart from
4449 certain job control functionality that is present in unix (ctrl+z does
4849 certain job control functionality that is present in unix (ctrl+z does
4450 "suspend"), the sh profile should provide you with most of the
4850 "suspend"), the sh profile should provide you with most of the
4451 functionality you use daily in system shell, and more. Invoke IPython
4851 functionality you use daily in system shell, and more. Invoke IPython
4452 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
4852 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
4453 the "pysh" shortcut in start menu.
4853 the "pysh" shortcut in start menu.
4454
4854
4455 If you want to use the features of sh profile as your defaults (which
4855 If you want to use the features of sh profile as your defaults (which
4456 might be a good idea if you use other profiles a lot of the time but
4856 might be a good idea if you use other profiles a lot of the time but
4457 still want the convenience of sh profile), add ``import ipy_profile_sh``
4857 still want the convenience of sh profile), add ``import ipy_profile_sh``
4458 to your ~/.ipython/ipy_user_conf.py.
4858 to your ~/.ipython/ipy_user_conf.py.
4459
4859
4460 The 'sh' profile is different from the default profile in that:
4860 The 'sh' profile is different from the default profile in that:
4461
4861
4462 * Prompt shows the current directory
4862 * Prompt shows the current directory
4463 * Spacing between prompts and input is more compact (no padding with
4863 * Spacing between prompts and input is more compact (no padding with
4464 empty lines). The startup banner is more compact as well.
4864 empty lines). The startup banner is more compact as well.
4465 * System commands are directly available (in alias table) without
4865 * System commands are directly available (in alias table) without
4466 requesting %rehashx - however, if you install new programs along
4866 requesting %rehashx - however, if you install new programs along
4467 your PATH, you might want to run %rehashx to update the persistent
4867 your PATH, you might want to run %rehashx to update the persistent
4468 alias table
4868 alias table
4469 * Macros are stored in raw format by default. That is, instead of
4869 * Macros are stored in raw format by default. That is, instead of
4470 '_ip.system("cat foo"), the macro will contain text 'cat foo')
4870 '_ip.system("cat foo"), the macro will contain text 'cat foo')
4471 * Autocall is in full mode
4871 * Autocall is in full mode
4472 * Calling "up" does "cd .."
4872 * Calling "up" does "cd .."
4473
4873
4474 The 'sh' profile is different from the now-obsolete (and unavailable)
4874 The 'sh' profile is different from the now-obsolete (and unavailable)
4475 'pysh' profile in that:
4875 'pysh' profile in that:
4476
4876
4477 * '$$var = command' and '$var = command' syntax is not supported
4877 * '$$var = command' and '$var = command' syntax is not supported
4478 * anymore. Use 'var = !command' instead (incidentally, this is
4878 * anymore. Use 'var = !command' instead (incidentally, this is
4479 * available in all IPython profiles). Note that !!command *will*
4879 * available in all IPython profiles). Note that !!command *will*
4480 * work.
4880 * work.
4481
4881
4482 Aliases
4882 Aliases
4483 -------
4883 -------
4484
4884
4485 All of your $PATH has been loaded as IPython aliases, so you should be
4885 All of your $PATH has been loaded as IPython aliases, so you should be
4486 able to type any normal system command and have it executed. See
4886 able to type any normal system command and have it executed. See
4487 %alias? and %unalias? for details on the alias facilities. See also
4887 %alias? and %unalias? for details on the alias facilities. See also
4488 %rehashx? for details on the mechanism used to load $PATH.
4888 %rehashx? for details on the mechanism used to load $PATH.
4489
4889
4490
4890
4491 Directory management
4891 Directory management
4492 --------------------
4892 --------------------
4493
4893
4494 Since each command passed by ipython to the underlying system is executed
4894 Since each command passed by ipython to the underlying system is executed
4495 in a subshell which exits immediately, you can NOT use !cd to navigate
4895 in a subshell which exits immediately, you can NOT use !cd to navigate
4496 the filesystem.
4896 the filesystem.
4497
4897
4498 IPython provides its own builtin '%cd' magic command to move in the
4898 IPython provides its own builtin '%cd' magic command to move in the
4499 filesystem (the % is not required with automagic on). It also maintains
4899 filesystem (the % is not required with automagic on). It also maintains
4500 a list of visited directories (use %dhist to see it) and allows direct
4900 a list of visited directories (use %dhist to see it) and allows direct
4501 switching to any of them. Type 'cd?' for more details.
4901 switching to any of them. Type 'cd?' for more details.
4502
4902
4503 %pushd, %popd and %dirs are provided for directory stack handling.
4903 %pushd, %popd and %dirs are provided for directory stack handling.
4504
4904
4505
4905
4506 Enabled extensions
4906 Enabled extensions
4507 ------------------
4907 ------------------
4508
4908
4509 Some extensions, listed below, are enabled as default in this profile.
4909 Some extensions, listed below, are enabled as default in this profile.
4510
4910
4511 envpersist
4911 envpersist
4512 ++++++++++
4912 ++++++++++
4513
4913
4514 %env can be used to "remember" environment variable manipulations. Examples::
4914 %env can be used to "remember" environment variable manipulations. Examples::
4515
4915
4516 %env - Show all environment variables
4916 %env - Show all environment variables
4517 %env VISUAL=jed - set VISUAL to jed
4917 %env VISUAL=jed - set VISUAL to jed
4518 %env PATH+=;/foo - append ;foo to PATH
4918 %env PATH+=;/foo - append ;foo to PATH
4519 %env PATH+=;/bar - also append ;bar to PATH
4919 %env PATH+=;/bar - also append ;bar to PATH
4520 %env PATH-=/wbin; - prepend /wbin; to PATH
4920 %env PATH-=/wbin; - prepend /wbin; to PATH
4521 %env -d VISUAL - forget VISUAL persistent val
4921 %env -d VISUAL - forget VISUAL persistent val
4522 %env -p - print all persistent env modifications
4922 %env -p - print all persistent env modifications
4523
4923
4524 ipy_which
4924 ipy_which
4525 +++++++++
4925 +++++++++
4526
4926
4527 %which magic command. Like 'which' in unix, but knows about ipython aliases.
4927 %which magic command. Like 'which' in unix, but knows about ipython aliases.
4528
4928
4529 Example::
4929 Example::
4530
4930
4531 [C:/ipython]|14> %which st
4931 [C:/ipython]|14> %which st
4532 st -> start .
4932 st -> start .
4533 [C:/ipython]|15> %which d
4933 [C:/ipython]|15> %which d
4534 d -> dir /w /og /on
4934 d -> dir /w /og /on
4535 [C:/ipython]|16> %which cp
4935 [C:/ipython]|16> %which cp
4536 cp -> cp
4936 cp -> cp
4537 == c:\bin\cp.exe
4937 == c:\bin\cp.exe
4538 c:\bin\cp.exe
4938 c:\bin\cp.exe
4539
4939
4540 ipy_app_completers
4940 ipy_app_completers
4541 ++++++++++++++++++
4941 ++++++++++++++++++
4542
4942
4543 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
4943 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
4544
4944
4545 ipy_rehashdir
4945 ipy_rehashdir
4546 +++++++++++++
4946 +++++++++++++
4547
4947
4548 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
4948 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
4549
4949
4550 [~]|22> cd c:/opt/PuTTY/
4950 [~]|22> cd c:/opt/PuTTY/
4551 [c:opt/PuTTY]|23> rehashdir .
4951 [c:opt/PuTTY]|23> rehashdir .
4552 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
4952 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
4553
4953
4554 Now, you can execute any of those commams directly::
4954 Now, you can execute any of those commams directly::
4555
4955
4556 [c:opt/PuTTY]|24> cd
4956 [c:opt/PuTTY]|24> cd
4557 [~]|25> putty
4957 [~]|25> putty
4558
4958
4559 (the putty window opens).
4959 (the putty window opens).
4560
4960
4561 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
4961 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
4562
4962
4563 [~]|27> for a in _23:
4963 [~]|27> for a in _23:
4564 |..> %store $a
4964 |..> %store $a
4565 |..>
4965 |..>
4566 |..>
4966 |..>
4567 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
4967 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
4568 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
4968 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
4569 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
4969 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
4570 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
4970 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
4571 ...
4971 ...
4572
4972
4573 mglob
4973 mglob
4574 +++++
4974 +++++
4575
4975
4576 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
4976 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
4577
4977
4578 [c:/ipython]|9> mglob *.py
4978 [c:/ipython]|9> mglob *.py
4579 [c:/ipython]|10> mglob *.py rec:*.txt
4979 [c:/ipython]|10> mglob *.py rec:*.txt
4580 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
4980 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
4581
4981
4582 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
4982 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
4583
4983
4584
4984
4585 Prompt customization
4985 Prompt customization
4586 --------------------
4986 --------------------
4587
4987
4588 The sh profile uses the following prompt configurations::
4988 The sh profile uses the following prompt configurations::
4589
4989
4590 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
4990 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>'
4591 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
4991 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>'
4592
4992
4593 You can change the prompt configuration to your liking by editing
4993 You can change the prompt configuration to your liking by editing
4594 ipy_user_conf.py.
4994 ipy_user_conf.py.
4595
4995
4596 String lists
4996 String lists
4597 ============
4997 ============
4598
4998
4599 String lists (IPython.genutils.SList) are handy way to process output
4999 String lists (IPython.genutils.SList) are handy way to process output
4600 from system commands. They are produced by ``var = !cmd`` syntax.
5000 from system commands. They are produced by ``var = !cmd`` syntax.
4601
5001
4602 First, we acquire the output of 'ls -l'::
5002 First, we acquire the output of 'ls -l'::
4603
5003
4604 [Q:doc/examples]|2> lines = !ls -l
5004 [Q:doc/examples]|2> lines = !ls -l
4605 ==
5005 ==
4606 ['total 23',
5006 ['total 23',
4607 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
5007 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
4608 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
5008 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
4609 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
5009 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
4610 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
5010 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
4611 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
5011 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
4612 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
5012 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
4613 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
5013 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
4614
5014
4615 Now, let's take a look at the contents of 'lines' (the first number is
5015 Now, let's take a look at the contents of 'lines' (the first number is
4616 the list element number)::
5016 the list element number)::
4617
5017
4618 [Q:doc/examples]|3> lines
5018 [Q:doc/examples]|3> lines
4619 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5019 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4620
5020
4621 0: total 23
5021 0: total 23
4622 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
5022 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
4623 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
5023 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
4624 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
5024 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
4625 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
5025 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
4626 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
5026 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
4627 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
5027 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
4628 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
5028 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
4629
5029
4630 Now, let's filter out the 'embed' lines::
5030 Now, let's filter out the 'embed' lines::
4631
5031
4632 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
5032 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
4633 [Q:doc/examples]|5> l2
5033 [Q:doc/examples]|5> l2
4634 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5034 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4635
5035
4636 0: total 23
5036 0: total 23
4637 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
5037 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
4638 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
5038 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
4639 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
5039 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
4640 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
5040 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
4641 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
5041 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
4642
5042
4643 Now, we want strings having just file names and permissions::
5043 Now, we want strings having just file names and permissions::
4644
5044
4645 [Q:doc/examples]|6> l2.fields(8,0)
5045 [Q:doc/examples]|6> l2.fields(8,0)
4646 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
5046 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
4647
5047
4648 0: total
5048 0: total
4649 1: example-demo.py -rw-rw-rw-
5049 1: example-demo.py -rw-rw-rw-
4650 2: example-gnuplot.py -rwxrwxrwx
5050 2: example-gnuplot.py -rwxrwxrwx
4651 3: extension.py -rwxrwxrwx
5051 3: extension.py -rwxrwxrwx
4652 4: seteditor.py -rwxrwxrwx
5052 4: seteditor.py -rwxrwxrwx
4653 5: seteditor.pyc -rwxrwxrwx
5053 5: seteditor.pyc -rwxrwxrwx
4654
5054
4655 Note how the line with 'total' does not raise IndexError.
5055 Note how the line with 'total' does not raise IndexError.
4656
5056
4657 If you want to split these (yielding lists), call fields() without
5057 If you want to split these (yielding lists), call fields() without
4658 arguments::
5058 arguments::
4659
5059
4660 [Q:doc/examples]|7> _.fields()
5060 [Q:doc/examples]|7> _.fields()
4661 <7>
5061 <7>
4662 [['total'],
5062 [['total'],
4663 ['example-demo.py', '-rw-rw-rw-'],
5063 ['example-demo.py', '-rw-rw-rw-'],
4664 ['example-gnuplot.py', '-rwxrwxrwx'],
5064 ['example-gnuplot.py', '-rwxrwxrwx'],
4665 ['extension.py', '-rwxrwxrwx'],
5065 ['extension.py', '-rwxrwxrwx'],
4666 ['seteditor.py', '-rwxrwxrwx'],
5066 ['seteditor.py', '-rwxrwxrwx'],
4667 ['seteditor.pyc', '-rwxrwxrwx']]
5067 ['seteditor.pyc', '-rwxrwxrwx']]
4668
5068
4669 If you want to pass these separated with spaces to a command (typical
5069 If you want to pass these separated with spaces to a command (typical
4670 for lists if files), use the .s property::
5070 for lists if files), use the .s property::
4671
5071
4672
5072
4673 [Q:doc/examples]|13> files = l2.fields(8).s
5073 [Q:doc/examples]|13> files = l2.fields(8).s
4674 [Q:doc/examples]|14> files
5074 [Q:doc/examples]|14> files
4675 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
5075 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
4676 [Q:doc/examples]|15> ls $files
5076 [Q:doc/examples]|15> ls $files
4677 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
5077 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
4678
5078
4679 SLists are inherited from normal python lists, so every list method is
5079 SLists are inherited from normal python lists, so every list method is
4680 available::
5080 available::
4681
5081
4682 [Q:doc/examples]|21> lines.append('hey')
5082 [Q:doc/examples]|21> lines.append('hey')
4683
5083
4684
5084
4685 Real world example: remove all files outside version control
5085 Real world example: remove all files outside version control
4686 ------------------------------------------------------------
5086 ------------------------------------------------------------
4687
5087
4688 First, capture output of "hg status"::
5088 First, capture output of "hg status"::
4689
5089
4690 [Q:/ipython]|28> out = !hg status
5090 [Q:/ipython]|28> out = !hg status
4691 ==
5091 ==
4692 ['M IPython\\Extensions\\ipy_kitcfg.py',
5092 ['M IPython\\Extensions\\ipy_kitcfg.py',
4693 'M IPython\\Extensions\\ipy_rehashdir.py',
5093 'M IPython\\Extensions\\ipy_rehashdir.py',
4694 ...
5094 ...
4695 '? build\\lib\\IPython\\Debugger.py',
5095 '? build\\lib\\IPython\\Debugger.py',
4696 '? build\\lib\\IPython\\Extensions\\InterpreterExec.py',
5096 '? build\\lib\\IPython\\Extensions\\InterpreterExec.py',
4697 '? build\\lib\\IPython\\Extensions\\InterpreterPasteInput.py',
5097 '? build\\lib\\IPython\\Extensions\\InterpreterPasteInput.py',
4698 ...
5098 ...
4699
5099
4700 (lines starting with ? are not under version control).
5100 (lines starting with ? are not under version control).
4701
5101
4702 ::
5102 ::
4703
5103
4704 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
5104 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
4705 [Q:/ipython]|36> junk
5105 [Q:/ipython]|36> junk
4706 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
5106 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
4707 ...
5107 ...
4708 10: build\bdist.win32\winexe\temp\_ctypes.py
5108 10: build\bdist.win32\winexe\temp\_ctypes.py
4709 11: build\bdist.win32\winexe\temp\_hashlib.py
5109 11: build\bdist.win32\winexe\temp\_hashlib.py
4710 12: build\bdist.win32\winexe\temp\_socket.py
5110 12: build\bdist.win32\winexe\temp\_socket.py
4711
5111
4712 Now we can just remove these files by doing 'rm $junk.s'.
5112 Now we can just remove these files by doing 'rm $junk.s'.
4713
5113
4714 The .s, .n, .p properties
5114 The .s, .n, .p properties
4715 -------------------------
5115 -------------------------
4716
5116
4717 The '.s' property returns one string where lines are separated by
5117 The '.s' property returns one string where lines are separated by
4718 single space (for convenient passing to system commands). The '.n'
5118 single space (for convenient passing to system commands). The '.n'
4719 property return one string where the lines are separated by '\n'
5119 property return one string where the lines are separated by '\n'
4720 (i.e. the original output of the function). If the items in string
5120 (i.e. the original output of the function). If the items in string
4721 list are file names, '.p' can be used to get a list of "path" objects
5121 list are file names, '.p' can be used to get a list of "path" objects
4722 for convenient file manipulation.
5122 for convenient file manipulation.
4723
5123
4724
5124
4725 Threading support
5125 Threading support
4726 =================
5126 =================
4727
5127
4728 WARNING: The threading support is still somewhat experimental, and it
5128 WARNING: The threading support is still somewhat experimental, and it
4729 has only seen reasonable testing under Linux. Threaded code is
5129 has only seen reasonable testing under Linux. Threaded code is
4730 particularly tricky to debug, and it tends to show extremely
5130 particularly tricky to debug, and it tends to show extremely
4731 platform-dependent behavior. Since I only have access to Linux machines,
5131 platform-dependent behavior. Since I only have access to Linux machines,
4732 I will have to rely on user's experiences and assistance for this area
5132 I will have to rely on user's experiences and assistance for this area
4733 of IPython to improve under other platforms.
5133 of IPython to improve under other platforms.
4734
5134
4735 IPython, via the -gthread , -qthread, -q4thread and -wthread options
5135 IPython, via the -gthread , -qthread, -q4thread and -wthread options
4736 (described in Sec. 5.1 <node5.html#sec:threading-opts>), can run in
5136 (described in Sec. `Threading options`_), can run in
4737 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
5137 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
4738 respectively. These GUI toolkits need to control the python main loop of
5138 respectively. These GUI toolkits need to control the python main loop of
4739 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
5139 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
4740 Qt4 or WXPython application will immediately freeze the shell.
5140 Qt4 or WXPython application will immediately freeze the shell.
4741
5141
4742 IPython, with one of these options (you can only use one at a time),
5142 IPython, with one of these options (you can only use one at a time),
4743 separates the graphical loop and IPython's code execution run into
5143 separates the graphical loop and IPython's code execution run into
4744 different threads. This allows you to test interactively (with %run, for
5144 different threads. This allows you to test interactively (with %run, for
4745 example) your GUI code without blocking.
5145 example) your GUI code without blocking.
4746
5146
4747 A nice mini-tutorial on using IPython along with the Qt Designer
5147 A nice mini-tutorial on using IPython along with the Qt Designer
4748 application is available at the SciPy wiki:
5148 application is available at the SciPy wiki:
4749 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
5149 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
4750
5150
4751
5151
4752 Tk issues
5152 Tk issues
4753 ---------
5153 ---------
4754
5154
4755 As indicated in Sec. 5.1 <node5.html#sec:threading-opts>, a special -tk
5155 As indicated in Sec. `Threading options`_, a special -tk option is
4756 option is provided to try and allow Tk graphical applications to coexist
5156 provided to try and allow Tk graphical applications to coexist
4757 interactively with WX, Qt or GTK ones. Whether this works at all,
5157 interactively with WX, Qt or GTK ones. Whether this works at all,
4758 however, is very platform and configuration dependent. Please experiment
5158 however, is very platform and configuration dependent. Please
4759 with simple test cases before committing to using this combination of Tk
5159 experiment with simple test cases before committing to using this
4760 and GTK/Qt/WX threading in a production environment.
5160 combination of Tk and GTK/Qt/WX threading in a production environment.
4761
5161
4762
5162
4763 I/O pitfalls
5163 I/O pitfalls
4764 ------------
5164 ------------
4765
5165
4766 Be mindful that the Python interpreter switches between threads every
5166 Be mindful that the Python interpreter switches between threads every
4767 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
5167 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
4768 value can be read by using the sys.getcheckinterval() function, and it
5168 value can be read by using the sys.getcheckinterval() function, and it
4769 can be reset via sys.setcheckinterval(N). This switching of threads can
5169 can be reset via sys.setcheckinterval(N). This switching of threads can
4770 cause subtly confusing effects if one of your threads is doing file I/O.
5170 cause subtly confusing effects if one of your threads is doing file I/O.
4771 In text mode, most systems only flush file buffers when they encounter a
5171 In text mode, most systems only flush file buffers when they encounter a
4772 '\n'. An instruction as simple as::
5172 '\n'. An instruction as simple as::
4773
5173
4774 print >> filehandle, ''hello world''
5174 print >> filehandle, ''hello world''
4775
5175
4776 actually consists of several bytecodes, so it is possible that the
5176 actually consists of several bytecodes, so it is possible that the
4777 newline does not reach your file before the next thread switch.
5177 newline does not reach your file before the next thread switch.
4778 Similarly, if you are writing to a file in binary mode, the file won't
5178 Similarly, if you are writing to a file in binary mode, the file won't
4779 be flushed until the buffer fills, and your other thread may see
5179 be flushed until the buffer fills, and your other thread may see
4780 apparently truncated files.
5180 apparently truncated files.
4781
5181
4782 For this reason, if you are using IPython's thread support and have (for
5182 For this reason, if you are using IPython's thread support and have (for
4783 example) a GUI application which will read data generated by files
5183 example) a GUI application which will read data generated by files
4784 written to from the IPython thread, the safest approach is to open all
5184 written to from the IPython thread, the safest approach is to open all
4785 of your files in unbuffered mode (the third argument to the file/open
5185 of your files in unbuffered mode (the third argument to the file/open
4786 function is the buffering value)::
5186 function is the buffering value)::
4787
5187
4788 filehandle = open(filename,mode,0)
5188 filehandle = open(filename,mode,0)
4789
5189
4790 This is obviously a brute force way of avoiding race conditions with the
5190 This is obviously a brute force way of avoiding race conditions with the
4791 file buffering. If you want to do it cleanly, and you have a resource
5191 file buffering. If you want to do it cleanly, and you have a resource
4792 which is being shared by the interactive IPython loop and your GUI
5192 which is being shared by the interactive IPython loop and your GUI
4793 thread, you should really handle it with thread locking and
5193 thread, you should really handle it with thread locking and
4794 syncrhonization properties. The Python documentation discusses these.
5194 syncrhonization properties. The Python documentation discusses these.
4795
5195
5196 .. _Interactive demos:
5197
4796 Interactive demos with IPython
5198 Interactive demos with IPython
4797 ==============================
5199 ==============================
4798
5200
4799 IPython ships with a basic system for running scripts interactively in
5201 IPython ships with a basic system for running scripts interactively in
4800 sections, useful when presenting code to audiences. A few tags embedded
5202 sections, useful when presenting code to audiences. A few tags embedded
4801 in comments (so that the script remains valid Python code) divide a file
5203 in comments (so that the script remains valid Python code) divide a file
4802 into separate blocks, and the demo can be run one block at a time, with
5204 into separate blocks, and the demo can be run one block at a time, with
4803 IPython printing (with syntax highlighting) the block before executing
5205 IPython printing (with syntax highlighting) the block before executing
4804 it, and returning to the interactive prompt after each block. The
5206 it, and returning to the interactive prompt after each block. The
4805 interactive namespace is updated after each block is run with the
5207 interactive namespace is updated after each block is run with the
4806 contents of the demo's namespace.
5208 contents of the demo's namespace.
4807
5209
4808 This allows you to show a piece of code, run it and then execute
5210 This allows you to show a piece of code, run it and then execute
4809 interactively commands based on the variables just created. Once you
5211 interactively commands based on the variables just created. Once you
4810 want to continue, you simply execute the next block of the demo. The
5212 want to continue, you simply execute the next block of the demo. The
4811 following listing shows the markup necessary for dividing a script into
5213 following listing shows the markup necessary for dividing a script into
4812 sections for execution as a demo::
5214 sections for execution as a demo::
4813
5215
4814
5216
4815 """A simple interactive demo to illustrate the use of IPython's Demo class.
5217 """A simple interactive demo to illustrate the use of IPython's Demo class.
4816
5218
4817 Any python script can be run as a demo, but that does little more than showing
5219 Any python script can be run as a demo, but that does little more than showing
4818 it on-screen, syntax-highlighted in one shot. If you add a little simple
5220 it on-screen, syntax-highlighted in one shot. If you add a little simple
4819 markup, you can stop at specified intervals and return to the ipython prompt,
5221 markup, you can stop at specified intervals and return to the ipython prompt,
4820 resuming execution later.
5222 resuming execution later.
4821 """
5223 """
4822
5224
4823 print 'Hello, welcome to an interactive IPython demo.'
5225 print 'Hello, welcome to an interactive IPython demo.'
4824 print 'Executing this block should require confirmation before proceeding,'
5226 print 'Executing this block should require confirmation before proceeding,'
4825 print 'unless auto_all has been set to true in the demo object'
5227 print 'unless auto_all has been set to true in the demo object'
4826
5228
4827 # The mark below defines a block boundary, which is a point where IPython will
5229 # The mark below defines a block boundary, which is a point where IPython will
4828 # stop execution and return to the interactive prompt.
5230 # stop execution and return to the interactive prompt.
4829 # Note that in actual interactive execution,
5231 # Note that in actual interactive execution,
4830 # <demo> --- stop ---
5232 # <demo> --- stop ---
4831
5233
4832 x = 1
5234 x = 1
4833 y = 2
5235 y = 2
4834
5236
4835 # <demo> --- stop ---
5237 # <demo> --- stop ---
4836
5238
4837 # the mark below makes this block as silent
5239 # the mark below makes this block as silent
4838 # <demo> silent
5240 # <demo> silent
4839
5241
4840 print 'This is a silent block, which gets executed but not printed.'
5242 print 'This is a silent block, which gets executed but not printed.'
4841
5243
4842 # <demo> --- stop ---
5244 # <demo> --- stop ---
4843 # <demo> auto
5245 # <demo> auto
4844 print 'This is an automatic block.'
5246 print 'This is an automatic block.'
4845 print 'It is executed without asking for confirmation, but printed.'
5247 print 'It is executed without asking for confirmation, but printed.'
4846 z = x+y
5248 z = x+y
4847
5249
4848 print 'z=',x
5250 print 'z=',x
4849
5251
4850 # <demo> --- stop ---
5252 # <demo> --- stop ---
4851 # This is just another normal block.
5253 # This is just another normal block.
4852 print 'z is now:', z
5254 print 'z is now:', z
4853
5255
4854 print 'bye!'
5256 print 'bye!'
4855
5257
4856 In order to run a file as a demo, you must first make a Demo object out
5258 In order to run a file as a demo, you must first make a Demo object out
4857 of it. If the file is named myscript.py, the following code will make a
5259 of it. If the file is named myscript.py, the following code will make a
4858 demo::
5260 demo::
4859
5261
4860 from IPython.demo import Demo
5262 from IPython.demo import Demo
4861
5263
4862 mydemo = Demo('myscript.py')
5264 mydemo = Demo('myscript.py')
4863
5265
4864 This creates the mydemo object, whose blocks you run one at a time by
5266 This creates the mydemo object, whose blocks you run one at a time by
4865 simply calling the object with no arguments. If you have autocall active
5267 simply calling the object with no arguments. If you have autocall active
4866 in IPython (the default), all you need to do is type::
5268 in IPython (the default), all you need to do is type::
4867
5269
4868 mydemo
5270 mydemo
4869
5271
4870 and IPython will call it, executing each block. Demo objects can be
5272 and IPython will call it, executing each block. Demo objects can be
4871 restarted, you can move forward or back skipping blocks, re-execute the
5273 restarted, you can move forward or back skipping blocks, re-execute the
4872 last block, etc. Simply use the Tab key on a demo object to see its
5274 last block, etc. Simply use the Tab key on a demo object to see its
4873 methods, and call '?' on them to see their docstrings for more usage
5275 methods, and call '?' on them to see their docstrings for more usage
4874 details. In addition, the demo module itself contains a comprehensive
5276 details. In addition, the demo module itself contains a comprehensive
4875 docstring, which you can access via::
5277 docstring, which you can access via::
4876
5278
4877 from IPython import demo
5279 from IPython import demo
4878
5280
4879 demo?
5281 demo?
4880
5282
4881 Limitations: It is important to note that these demos are limited to
5283 Limitations: It is important to note that these demos are limited to
4882 fairly simple uses. In particular, you can not put division marks in
5284 fairly simple uses. In particular, you can not put division marks in
4883 indented code (loops, if statements, function definitions, etc.)
5285 indented code (loops, if statements, function definitions, etc.)
4884 Supporting something like this would basically require tracking the
5286 Supporting something like this would basically require tracking the
4885 internal execution state of the Python interpreter, so only top-level
5287 internal execution state of the Python interpreter, so only top-level
4886 divisions are allowed. If you want to be able to open an IPython
5288 divisions are allowed. If you want to be able to open an IPython
4887 instance at an arbitrary point in a program, you can use IPython's
5289 instance at an arbitrary point in a program, you can use IPython's
4888 embedding facilities, described in detail in Sec. 9
5290 embedding facilities, described in detail in Sec. 9
4889
5291
4890
5292
5293 .. _Matplotlib support:
5294
4891 Plotting with matplotlib
5295 Plotting with matplotlib
4892 ========================
5296 ========================
4893
5297
4894 The matplotlib library (http://matplotlib.sourceforge.net
5298 The matplotlib library (http://matplotlib.sourceforge.net
4895 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
5299 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
4896 Python. Matplotlib can produce plots on screen using a variety of GUI
5300 Python. Matplotlib can produce plots on screen using a variety of GUI
4897 toolkits, including Tk, GTK and WXPython. It also provides a number of
5301 toolkits, including Tk, GTK and WXPython. It also provides a number of
4898 commands useful for scientific computing, all with a syntax compatible
5302 commands useful for scientific computing, all with a syntax compatible
4899 with that of the popular Matlab program.
5303 with that of the popular Matlab program.
4900
5304
4901 IPython accepts the special option -pylab (Sec. 5.2
5305 IPython accepts the special option -pylab (Sec. `Command line
4902 <node5.html#sec:cmd-line-opts>). This configures it to support
5306 options`_). This configures it to support matplotlib, honoring the
4903 matplotlib, honoring the settings in the .matplotlibrc file. IPython
5307 settings in the .matplotlibrc file. IPython will detect the user's
4904 will detect the user's choice of matplotlib GUI backend, and
5308 choice of matplotlib GUI backend, and automatically select the proper
4905 automatically select the proper threading model to prevent blocking. It
5309 threading model to prevent blocking. It also sets matplotlib in
4906 also sets matplotlib in interactive mode and modifies %run slightly, so
5310 interactive mode and modifies %run slightly, so that any
4907 that any matplotlib-based script can be executed using %run and the
5311 matplotlib-based script can be executed using %run and the final
4908 final show() command does not block the interactive shell.
5312 show() command does not block the interactive shell.
4909
5313
4910 The -pylab option must be given first in order for IPython to configure
5314 The -pylab option must be given first in order for IPython to
4911 its threading mode. However, you can still issue other options
5315 configure its threading mode. However, you can still issue other
4912 afterwards. This allows you to have a matplotlib-based environment
5316 options afterwards. This allows you to have a matplotlib-based
4913 customized with additional modules using the standard IPython profile
5317 environment customized with additional modules using the standard
4914 mechanism (Sec. 7.3 <node7.html#sec:profiles>): ''ipython -pylab -p
5318 IPython profile mechanism (Sec. Profiles_): ''ipython -pylab -p
4915 myprofile'' will load the profile defined in ipythonrc-myprofile after
5319 myprofile'' will load the profile defined in ipythonrc-myprofile after
4916 configuring matplotlib.
5320 configuring matplotlib.
4917
5321
4918 IPython Extension Api
5322 IPython Extension Api
4919 =====================
5323 =====================
4920
5324
4921 IPython api (defined in IPython/ipapi.py) is the public api that
5325 IPython api (defined in IPython/ipapi.py) is the public api that
4922 should be used for
5326 should be used for
4923
5327
4924 * Configuration of user preferences (.ipython/ipy_user_conf.py)
5328 * Configuration of user preferences (.ipython/ipy_user_conf.py)
4925 * Creating new profiles (.ipython/ipy_profile_PROFILENAME.py)
5329 * Creating new profiles (.ipython/ipy_profile_PROFILENAME.py)
4926 * Writing extensions
5330 * Writing extensions
4927
5331
4928 Note that by using the extension api for configuration (editing
5332 Note that by using the extension api for configuration (editing
4929 ipy_user_conf.py instead of ipythonrc), you get better validity checks
5333 ipy_user_conf.py instead of ipythonrc), you get better validity checks
4930 and get richer functionality - for example, you can import an
5334 and get richer functionality - for example, you can import an
4931 extension and call functions in it to configure it for your purposes.
5335 extension and call functions in it to configure it for your purposes.
4932
5336
4933 For an example extension (the 'sh' profile), see
5337 For an example extension (the 'sh' profile), see
4934 IPython/Extensions/ipy_profile_sh.py.
5338 IPython/Extensions/ipy_profile_sh.py.
4935
5339
4936 For the last word on what's available, see the source code of
5340 For the last word on what's available, see the source code of
4937 IPython/ipapi.py.
5341 IPython/ipapi.py.
4938
5342
4939
5343
4940 Getting started
5344 Getting started
4941 ---------------
5345 ---------------
4942
5346
4943 If you want to define an extension, create a normal python module that
5347 If you want to define an extension, create a normal python module that
4944 can be imported. The module will access IPython functionality through
5348 can be imported. The module will access IPython functionality through
4945 the 'ip' object defined below.
5349 the 'ip' object defined below.
4946
5350
4947 If you are creating a new profile (e.g. foobar), name the module as
5351 If you are creating a new profile (e.g. foobar), name the module as
4948 'ipy_profile_foobar.py' and put it in your ~/.ipython directory. Then,
5352 'ipy_profile_foobar.py' and put it in your ~/.ipython directory. Then,
4949 when you start ipython with the '-p foobar' argument, the module is
5353 when you start ipython with the '-p foobar' argument, the module is
4950 automatically imported on ipython startup.
5354 automatically imported on ipython startup.
4951
5355
4952 If you are just doing some per-user configuration, you can either
5356 If you are just doing some per-user configuration, you can either
4953
5357
4954 * Put the commands directly into ipy_user_conf.py.
5358 * Put the commands directly into ipy_user_conf.py.
4955
5359
4956 * Create a new module with your customization code and import *that*
5360 * Create a new module with your customization code and import *that*
4957 module in ipy_user_conf.py. This is preferable to the first approach,
5361 module in ipy_user_conf.py. This is preferable to the first approach,
4958 because now you can reuse and distribute your customization code.
5362 because now you can reuse and distribute your customization code.
4959
5363
4960 Getting a handle to the api
5364 Getting a handle to the api
4961 ---------------------------
5365 ---------------------------
4962
5366
4963 Put this in the start of your module::
5367 Put this in the start of your module::
4964
5368
4965 #!python
5369 #!python
4966 import IPython.ipapi
5370 import IPython.ipapi
4967 ip = IPython.ipapi.get()
5371 ip = IPython.ipapi.get()
4968
5372
4969 The 'ip' object will then be used for accessing IPython
5373 The 'ip' object will then be used for accessing IPython
4970 functionality. 'ip' will mean this api object in all the following
5374 functionality. 'ip' will mean this api object in all the following
4971 code snippets. The same 'ip' that we just acquired is always
5375 code snippets. The same 'ip' that we just acquired is always
4972 accessible in interactive IPython sessions by the name _ip - play with
5376 accessible in interactive IPython sessions by the name _ip - play with
4973 it like this::
5377 it like this::
4974
5378
4975 [~\_ipython]|81> a = 10
5379 [~\_ipython]|81> a = 10
4976 [~\_ipython]|82> _ip.e
5380 [~\_ipython]|82> _ip.e
4977 _ip.ev _ip.ex _ip.expose_magic
5381 _ip.ev _ip.ex _ip.expose_magic
4978 [~\_ipython]|82> _ip.ev('a+13')
5382 [~\_ipython]|82> _ip.ev('a+13')
4979 <82> 23
5383 <82> 23
4980
5384
4981 The _ip object is also used in some examples in this document - it can
5385 The _ip object is also used in some examples in this document - it can
4982 be substituted by 'ip' in non-interactive use.
5386 be substituted by 'ip' in non-interactive use.
4983
5387
4984 Changing options
5388 Changing options
4985 ----------------
5389 ----------------
4986
5390
4987 The ip object has 'options' attribute that can be used te get/set
5391 The ip object has 'options' attribute that can be used te get/set
4988 configuration options (just as in the ipythonrc file)::
5392 configuration options (just as in the ipythonrc file)::
4989
5393
4990 o = ip.options
5394 o = ip.options
4991 o.autocall = 2
5395 o.autocall = 2
4992 o.automagic = 1
5396 o.automagic = 1
4993
5397
4994 Executing statements in IPython namespace with 'ex' and 'ev'
5398 Executing statements in IPython namespace with 'ex' and 'ev'
4995 ------------------------------------------------------------
5399 ------------------------------------------------------------
4996
5400
4997 Often, you want to e.g. import some module or define something that
5401 Often, you want to e.g. import some module or define something that
4998 should be visible in IPython namespace. Use ``ip.ev`` to
5402 should be visible in IPython namespace. Use ``ip.ev`` to
4999 *evaluate* (calculate the value of) expression and ``ip.ex`` to
5403 *evaluate* (calculate the value of) expression and ``ip.ex`` to
5000 '''execute''' a statement::
5404 '''execute''' a statement::
5001
5405
5002 # path module will be visible to the interactive session
5406 # path module will be visible to the interactive session
5003 ip.ex("from path import path" )
5407 ip.ex("from path import path" )
5004
5408
5005 # define a handy function 'up' that changes the working directory
5409 # define a handy function 'up' that changes the working directory
5006
5410
5007 ip.ex('import os')
5411 ip.ex('import os')
5008 ip.ex("def up(): os.chdir('..')")
5412 ip.ex("def up(): os.chdir('..')")
5009
5413
5010
5414
5011 # _i2 has the input history entry #2, print its value in uppercase.
5415 # _i2 has the input history entry #2, print its value in uppercase.
5012 print ip.ev('_i2.upper()')
5416 print ip.ev('_i2.upper()')
5013
5417
5014 Accessing the IPython namespace
5418 Accessing the IPython namespace
5015 -------------------------------
5419 -------------------------------
5016
5420
5017 ip.user_ns attribute has a dictionary containing the IPython global
5421 ip.user_ns attribute has a dictionary containing the IPython global
5018 namespace (the namespace visible in the interactive session).
5422 namespace (the namespace visible in the interactive session).
5019
5423
5020 ::
5424 ::
5021
5425
5022 [~\_ipython]|84> tauno = 555
5426 [~\_ipython]|84> tauno = 555
5023 [~\_ipython]|85> _ip.user_ns['tauno']
5427 [~\_ipython]|85> _ip.user_ns['tauno']
5024 <85> 555
5428 <85> 555
5025
5429
5026 Defining new magic commands
5430 Defining new magic commands
5027 ---------------------------
5431 ---------------------------
5028
5432
5029 The following example defines a new magic command, %impall. What the
5433 The following example defines a new magic command, %impall. What the
5030 command does should be obvious::
5434 command does should be obvious::
5031
5435
5032 def doimp(self, arg):
5436 def doimp(self, arg):
5033 ip = self.api
5437 ip = self.api
5034 ip.ex("import %s; reload(%s); from %s import *" % (
5438 ip.ex("import %s; reload(%s); from %s import *" % (
5035 arg,arg,arg)
5439 arg,arg,arg)
5036 )
5440 )
5037
5441
5038 ip.expose_magic('impall', doimp)
5442 ip.expose_magic('impall', doimp)
5039
5443
5040 Things to observe in this example:
5444 Things to observe in this example:
5041
5445
5042 * Define a function that implements the magic command using the
5446 * Define a function that implements the magic command using the
5043 ipapi methods defined in this document
5447 ipapi methods defined in this document
5044 * The first argument of the function is 'self', i.e. the
5448 * The first argument of the function is 'self', i.e. the
5045 interpreter object. It shouldn't be used directly. however.
5449 interpreter object. It shouldn't be used directly. however.
5046 The interpreter object is probably *not* going to remain stable
5450 The interpreter object is probably *not* going to remain stable
5047 through IPython versions.
5451 through IPython versions.
5048 * Access the ipapi through 'self.api' instead of the global 'ip' object.
5452 * Access the ipapi through 'self.api' instead of the global 'ip' object.
5049 * All the text following the magic command on the command line is
5453 * All the text following the magic command on the command line is
5050 contained in the second argument
5454 contained in the second argument
5051 * Expose the magic by ip.expose_magic()
5455 * Expose the magic by ip.expose_magic()
5052
5456
5053
5457
5054 Calling magic functions and system commands
5458 Calling magic functions and system commands
5055 -------------------------------------------
5459 -------------------------------------------
5056
5460
5057 Use ip.magic() to execute a magic function, and ip.system() to execute
5461 Use ip.magic() to execute a magic function, and ip.system() to execute
5058 a system command::
5462 a system command::
5059
5463
5060 # go to a bookmark
5464 # go to a bookmark
5061 ip.magic('%cd -b relfiles')
5465 ip.magic('%cd -b relfiles')
5062
5466
5063 # execute 'ls -F' system command. Interchangeable with os.system('ls'), really.
5467 # execute 'ls -F' system command. Interchangeable with os.system('ls'), really.
5064 ip.system('ls -F')
5468 ip.system('ls -F')
5065
5469
5066 Launching IPython instance from normal python code
5470 Launching IPython instance from normal python code
5067 --------------------------------------------------
5471 --------------------------------------------------
5068
5472
5069 Use ipapi.launch_new_instance() with an argument that specifies the
5473 Use ipapi.launch_new_instance() with an argument that specifies the
5070 namespace to use. This can be useful for trivially embedding IPython
5474 namespace to use. This can be useful for trivially embedding IPython
5071 into your program. Here's an example of normal python program test.py
5475 into your program. Here's an example of normal python program test.py
5072 ('''without''' an existing IPython session) that launches an IPython
5476 ('''without''' an existing IPython session) that launches an IPython
5073 interpreter and regains control when the interpreter is exited::
5477 interpreter and regains control when the interpreter is exited::
5074
5478
5075 [ipython]|1> cat test.py
5479 [ipython]|1> cat test.py
5076 my_ns = dict(
5480 my_ns = dict(
5077 kissa = 15,
5481 kissa = 15,
5078 koira = 16)
5482 koira = 16)
5079 import IPython.ipapi
5483 import IPython.ipapi
5080 print "launching IPython instance"
5484 print "launching IPython instance"
5081 IPython.ipapi.launch_new_instance(my_ns)
5485 IPython.ipapi.launch_new_instance(my_ns)
5082 print "Exited IPython instance!"
5486 print "Exited IPython instance!"
5083 print "New vals:",my_ns['kissa'], my_ns['koira']
5487 print "New vals:",my_ns['kissa'], my_ns['koira']
5084
5488
5085 And here's what it looks like when run (note how we don't start it
5489 And here's what it looks like when run (note how we don't start it
5086 from an ipython session)::
5490 from an ipython session)::
5087
5491
5088 Q:\ipython>python test.py
5492 Q:\ipython>python test.py
5089 launching IPython instance
5493 launching IPython instance
5090 Py 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] IPy 0.7.3b3.r1975
5494 Py 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] IPy 0.7.3b3.r1975
5091 [ipython]|1> kissa = 444
5495 [ipython]|1> kissa = 444
5092 [ipython]|2> koira = 555
5496 [ipython]|2> koira = 555
5093 [ipython]|3> Exit
5497 [ipython]|3> Exit
5094 Exited IPython instance!
5498 Exited IPython instance!
5095 New vals: 444 555
5499 New vals: 444 555
5096
5500
5097 Accessing unexposed functionality
5501 Accessing unexposed functionality
5098 ---------------------------------
5502 ---------------------------------
5099
5503
5100 There are still many features that are not exposed via the ipapi. If
5504 There are still many features that are not exposed via the ipapi. If
5101 you can't avoid using them, you can use the functionality in
5505 you can't avoid using them, you can use the functionality in
5102 InteractiveShell object (central IPython session class, defined in
5506 InteractiveShell object (central IPython session class, defined in
5103 iplib.py) through ip.IP.
5507 iplib.py) through ip.IP.
5104
5508
5105 For example::
5509 For example::
5106
5510
5107 [~]|7> _ip.IP.expand_aliases('np','myfile.py')
5511 [~]|7> _ip.IP.expand_aliases('np','myfile.py')
5108 <7> 'c:/opt/Notepad++/notepad++.exe myfile.py'
5512 <7> 'c:/opt/Notepad++/notepad++.exe myfile.py'
5109 [~]|8>
5513 [~]|8>
5110
5514
5111 Still, it's preferable that if you encounter such a feature, contact
5515 Still, it's preferable that if you encounter such a feature, contact
5112 the IPython team and request that the functionality be exposed in a
5516 the IPython team and request that the functionality be exposed in a
5113 future version of IPython. Things not in ipapi are more likely to
5517 future version of IPython. Things not in ipapi are more likely to
5114 change over time.
5518 change over time.
5115
5519
5116 Provided extensions
5520 Provided extensions
5117 ===================
5521 ===================
5118
5522
5119 You can see the list of available extensions (and profiles) by doing
5523 You can see the list of available extensions (and profiles) by doing
5120 ``import ipy_<TAB>``. Some extensions don't have the ``ipy_`` prefix in
5524 ``import ipy_<TAB>``. Some extensions don't have the ``ipy_`` prefix in
5121 module name, so you may need to see the contents of IPython/Extensions
5525 module name, so you may need to see the contents of IPython/Extensions
5122 folder to see what's available.
5526 folder to see what's available.
5123
5527
5124 You can see a brief documentation of an extension by looking at the
5528 You can see a brief documentation of an extension by looking at the
5125 module docstring::
5529 module docstring::
5126
5530
5127 [c:p/ipython_main]|190> import ipy_fsops
5531 [c:p/ipython_main]|190> import ipy_fsops
5128 [c:p/ipython_main]|191> ipy_fsops?
5532 [c:p/ipython_main]|191> ipy_fsops?
5129
5533
5130 ...
5534 ...
5131
5535
5132 Docstring:
5536 Docstring:
5133 File system operations
5537 File system operations
5134
5538
5135 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
5539 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
5136 imkdir, igrep).
5540 imkdir, igrep).
5137
5541
5138 You can also install your own extensions - the recommended way is to
5542 You can also install your own extensions - the recommended way is to
5139 just copy the module to ~/.ipython. Extensions are typically enabled
5543 just copy the module to ~/.ipython. Extensions are typically enabled
5140 by just importing them (e.g. in ipy_user_conf.py), but some extensions
5544 by just importing them (e.g. in ipy_user_conf.py), but some extensions
5141 require additional steps, for example::
5545 require additional steps, for example::
5142
5546
5143 [c:p]|192> import ipy_traits_completer
5547 [c:p]|192> import ipy_traits_completer
5144 [c:p]|193> ipy_traits_completer.activate()
5548 [c:p]|193> ipy_traits_completer.activate()
5145
5549
5146 Note that extensions, even if provided in the stock IPython
5550 Note that extensions, even if provided in the stock IPython
5147 installation, are not guaranteed to have the same requirements as the
5551 installation, are not guaranteed to have the same requirements as the
5148 rest of IPython - an extension may require external libraries or a
5552 rest of IPython - an extension may require external libraries or a
5149 newer version of Python than what IPython officially requires. An
5553 newer version of Python than what IPython officially requires. An
5150 extension may also be under a more restrictive license than IPython
5554 extension may also be under a more restrictive license than IPython
5151 (e.g. ipy_bzr is under GPL).
5555 (e.g. ipy_bzr is under GPL).
5152
5556
5153 Just for reference, the list of bundled extensions at the time of
5557 Just for reference, the list of bundled extensions at the time of
5154 writing is below:
5558 writing is below:
5155
5559
5156 astyle.py clearcmd.py envpersist.py ext_rescapture.py ibrowse.py
5560 astyle.py clearcmd.py envpersist.py ext_rescapture.py ibrowse.py
5157 igrid.py InterpreterExec.py InterpreterPasteInput.py ipipe.py
5561 igrid.py InterpreterExec.py InterpreterPasteInput.py ipipe.py
5158 ipy_app_completers.py ipy_autoreload.py ipy_bzr.py ipy_completers.py
5562 ipy_app_completers.py ipy_autoreload.py ipy_bzr.py ipy_completers.py
5159 ipy_constants.py ipy_defaults.py ipy_editors.py ipy_exportdb.py
5563 ipy_constants.py ipy_defaults.py ipy_editors.py ipy_exportdb.py
5160 ipy_extutil.py ipy_fsops.py ipy_gnuglobal.py ipy_kitcfg.py
5564 ipy_extutil.py ipy_fsops.py ipy_gnuglobal.py ipy_kitcfg.py
5161 ipy_legacy.py ipy_leo.py ipy_p4.py ipy_profile_doctest.py
5565 ipy_legacy.py ipy_leo.py ipy_p4.py ipy_profile_doctest.py
5162 ipy_profile_none.py ipy_profile_scipy.py ipy_profile_sh.py
5566 ipy_profile_none.py ipy_profile_scipy.py ipy_profile_sh.py
5163 ipy_profile_zope.py ipy_pydb.py ipy_rehashdir.py ipy_render.py
5567 ipy_profile_zope.py ipy_pydb.py ipy_rehashdir.py ipy_render.py
5164 ipy_server.py ipy_signals.py ipy_stock_completers.py
5568 ipy_server.py ipy_signals.py ipy_stock_completers.py
5165 ipy_system_conf.py ipy_traits_completer.py ipy_vimserver.py
5569 ipy_system_conf.py ipy_traits_completer.py ipy_vimserver.py
5166 ipy_which.py ipy_workdir.py jobctrl.py ledit.py numeric_formats.py
5570 ipy_which.py ipy_workdir.py jobctrl.py ledit.py numeric_formats.py
5167 PhysicalQInput.py PhysicalQInteractive.py pickleshare.py
5571 PhysicalQInput.py PhysicalQInteractive.py pickleshare.py
5168 pspersistence.py win32clip.py __init__.py
5572 pspersistence.py win32clip.py __init__.py
5169
5573
5170 Reporting bugs
5574 Reporting bugs
5171 ==============
5575 ==============
5172
5576
5173 Automatic crash reports
5577 Automatic crash reports
5174 -----------------------
5578 -----------------------
5175
5579
5176 Ideally, IPython itself shouldn't crash. It will catch exceptions
5580 Ideally, IPython itself shouldn't crash. It will catch exceptions
5177 produced by you, but bugs in its internals will still crash it.
5581 produced by you, but bugs in its internals will still crash it.
5178
5582
5179 In such a situation, IPython will leave a file named
5583 In such a situation, IPython will leave a file named
5180 IPython_crash_report.txt in your IPYTHONDIR directory (that way if
5584 IPython_crash_report.txt in your IPYTHONDIR directory (that way if
5181 crashes happen several times it won't litter many directories, the
5585 crashes happen several times it won't litter many directories, the
5182 post-mortem file is always located in the same place and new occurrences
5586 post-mortem file is always located in the same place and new
5183 just overwrite the previous one). If you can mail this file to the
5587 occurrences just overwrite the previous one). If you can mail this
5184 developers (see sec. 20 <node20.html#sec:credits> for names and
5588 file to the developers (see sec. credits_ for names and addresses), it
5185 addresses), it will help us a lot in understanding the cause of the
5589 will help us a lot in understanding the cause of the problem and
5186 problem and fixing it sooner.
5590 fixing it sooner.
5187
5591
5188
5592
5189 The bug tracker
5593 The bug tracker
5190 ---------------
5594 ---------------
5191
5595
5192 IPython also has an online bug-tracker, located at
5596 IPython also has an online bug-tracker, located at
5193 http://projects.scipy.org/ipython/ipython/report/1. In addition to
5597 http://projects.scipy.org/ipython/ipython/report/1. In addition to
5194 mailing the developers, it would be a good idea to file a bug report
5598 mailing the developers, it would be a good idea to file a bug report
5195 here. This will ensure that the issue is properly followed to
5599 here. This will ensure that the issue is properly followed to
5196 conclusion. To report new bugs you will have to register first.
5600 conclusion. To report new bugs you will have to register first.
5197
5601
5198 You can also use this bug tracker to file feature requests.
5602 You can also use this bug tracker to file feature requests.
5199
5603
5200 Brief history
5604 Brief history
5201 =============
5605 =============
5202
5606
5203
5607
5204 Origins
5608 Origins
5205 -------
5609 -------
5206
5610
5207 The current IPython system grew out of the following three projects:
5611 The current IPython system grew out of the following three projects:
5208
5612
5209 * [ipython] by Fernando Pérez. I was working on adding
5613 * [ipython] by Fernando Pérez. I was working on adding
5210 Mathematica-type prompts and a flexible configuration system
5614 Mathematica-type prompts and a flexible configuration system
5211 (something better than $PYTHONSTARTUP) to the standard Python
5615 (something better than $PYTHONSTARTUP) to the standard Python
5212 interactive interpreter.
5616 interactive interpreter.
5213 * [IPP] by Janko Hauser. Very well organized, great usability. Had
5617 * [IPP] by Janko Hauser. Very well organized, great usability. Had
5214 an old help system. IPP was used as the 'container' code into
5618 an old help system. IPP was used as the 'container' code into
5215 which I added the functionality from ipython and LazyPython.
5619 which I added the functionality from ipython and LazyPython.
5216 * [LazyPython] by Nathan Gray. Simple but very powerful. The quick
5620 * [LazyPython] by Nathan Gray. Simple but very powerful. The quick
5217 syntax (auto parens, auto quotes) and verbose/colored tracebacks
5621 syntax (auto parens, auto quotes) and verbose/colored tracebacks
5218 were all taken from here.
5622 were all taken from here.
5219
5623
5220 When I found out (see sec. 20 <node20.html#figgins>) about IPP and
5624 When I found out about IPP and LazyPython I tried to join all three
5221 LazyPython I tried to join all three into a unified system. I thought
5625 into a unified system. I thought this could provide a very nice
5222 this could provide a very nice working environment, both for regular
5626 working environment, both for regular programming and scientific
5223 programming and scientific computing: shell-like features, IDL/Matlab
5627 computing: shell-like features, IDL/Matlab numerics, Mathematica-type
5224 numerics, Mathematica-type prompt history and great object introspection
5628 prompt history and great object introspection and help facilities. I
5225 and help facilities. I think it worked reasonably well, though it was a
5629 think it worked reasonably well, though it was a lot more work than I
5226 lot more work than I had initially planned.
5630 had initially planned.
5227
5631
5228
5632
5229 Current status
5633 Current status
5230 --------------
5634 --------------
5231
5635
5232 The above listed features work, and quite well for the most part. But
5636 The above listed features work, and quite well for the most part. But
5233 until a major internal restructuring is done (see below), only bug
5637 until a major internal restructuring is done (see below), only bug
5234 fixing will be done, no other features will be added (unless very minor
5638 fixing will be done, no other features will be added (unless very minor
5235 and well localized in the cleaner parts of the code).
5639 and well localized in the cleaner parts of the code).
5236
5640
5237 IPython consists of some 18000 lines of pure python code, of which
5641 IPython consists of some 18000 lines of pure python code, of which
5238 roughly two thirds is reasonably clean. The rest is, messy code which
5642 roughly two thirds is reasonably clean. The rest is, messy code which
5239 needs a massive restructuring before any further major work is done.
5643 needs a massive restructuring before any further major work is done.
5240 Even the messy code is fairly well documented though, and most of the
5644 Even the messy code is fairly well documented though, and most of the
5241 problems in the (non-existent) class design are well pointed to by a
5645 problems in the (non-existent) class design are well pointed to by a
5242 PyChecker run. So the rewriting work isn't that bad, it will just be
5646 PyChecker run. So the rewriting work isn't that bad, it will just be
5243 time-consuming.
5647 time-consuming.
5244
5648
5245
5649
5246 Future
5650 Future
5247 ------
5651 ------
5248
5652
5249 See the separate new_design document for details. Ultimately, I would
5653 See the separate new_design document for details. Ultimately, I would
5250 like to see IPython become part of the standard Python distribution as a
5654 like to see IPython become part of the standard Python distribution as a
5251 'big brother with batteries' to the standard Python interactive
5655 'big brother with batteries' to the standard Python interactive
5252 interpreter. But that will never happen with the current state of the
5656 interpreter. But that will never happen with the current state of the
5253 code, so all contributions are welcome.
5657 code, so all contributions are welcome.
5254
5658
5255 License
5659 License
5256 =======
5660 =======
5257
5661
5258 IPython is released under the terms of the BSD license, whose general
5662 IPython is released under the terms of the BSD license, whose general
5259 form can be found at:
5663 form can be found at:
5260 http://www.opensource.org/licenses/bsd-license.php. The full text of the
5664 http://www.opensource.org/licenses/bsd-license.php. The full text of the
5261 IPython license is reproduced below::
5665 IPython license is reproduced below::
5262
5666
5263 IPython is released under a BSD-type license.
5667 IPython is released under a BSD-type license.
5264
5668
5265 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez
5669 Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez
5266 <fperez@colorado.edu>.
5670 <fperez@colorado.edu>.
5267
5671
5268 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
5672 Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and
5269 Nathaniel Gray <n8gray@caltech.edu>.
5673 Nathaniel Gray <n8gray@caltech.edu>.
5270
5674
5271 All rights reserved.
5675 All rights reserved.
5272
5676
5273 Redistribution and use in source and binary forms, with or without
5677 Redistribution and use in source and binary forms, with or without
5274 modification, are permitted provided that the following conditions
5678 modification, are permitted provided that the following conditions
5275 are met:
5679 are met:
5276
5680
5277 a. Redistributions of source code must retain the above copyright
5681 a. Redistributions of source code must retain the above copyright
5278 notice, this list of conditions and the following disclaimer.
5682 notice, this list of conditions and the following disclaimer.
5279
5683
5280 b. Redistributions in binary form must reproduce the above copyright
5684 b. Redistributions in binary form must reproduce the above copyright
5281 notice, this list of conditions and the following disclaimer in the
5685 notice, this list of conditions and the following disclaimer in the
5282 documentation and/or other materials provided with the distribution.
5686 documentation and/or other materials provided with the distribution.
5283
5687
5284 c. Neither the name of the copyright holders nor the names of any
5688 c. Neither the name of the copyright holders nor the names of any
5285 contributors to this software may be used to endorse or promote
5689 contributors to this software may be used to endorse or promote
5286 products derived from this software without specific prior written
5690 products derived from this software without specific prior written
5287 permission.
5691 permission.
5288
5692
5289 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5693 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5290 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5694 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5291 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
5695 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
5292 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5696 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
5293 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
5697 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
5294 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
5698 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
5295 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
5699 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
5296 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
5700 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
5297 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
5701 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
5298 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
5702 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
5299 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
5703 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
5300 POSSIBILITY OF SUCH DAMAGE.
5704 POSSIBILITY OF SUCH DAMAGE.
5301
5705
5302 Individual authors are the holders of the copyright for their code and
5706 Individual authors are the holders of the copyright for their code and
5303 are listed in each file.
5707 are listed in each file.
5304
5708
5305 Some files (DPyGetOpt.py, for example) may be licensed under different
5709 Some files (DPyGetOpt.py, for example) may be licensed under different
5306 conditions. Ultimately each file indicates clearly the conditions under
5710 conditions. Ultimately each file indicates clearly the conditions under
5307 which its author/authors have decided to publish the code.
5711 which its author/authors have decided to publish the code.
5308
5712
5309 Versions of IPython up to and including 0.6.3 were released under the
5713 Versions of IPython up to and including 0.6.3 were released under the
5310 GNU Lesser General Public License (LGPL), available at
5714 GNU Lesser General Public License (LGPL), available at
5311 http://www.gnu.org/copyleft/lesser.html.
5715 http://www.gnu.org/copyleft/lesser.html.
5312
5716
5313 Credits
5717 Credits
5314 =======
5718 =======
5315
5719
5316 IPython is mainly developed by Fernando Pérez
5720 IPython is mainly developed by Fernando Pérez
5317 <Fernando.Perez@colorado.edu>, but the project was born from mixing in
5721 <Fernando.Perez@colorado.edu>, but the project was born from mixing in
5318 Fernando's code with the IPP project by Janko Hauser
5722 Fernando's code with the IPP project by Janko Hauser
5319 <jhauser-AT-zscout.de> and LazyPython by Nathan Gray
5723 <jhauser-AT-zscout.de> and LazyPython by Nathan Gray
5320 <n8gray-AT-caltech.edu>. For all IPython-related requests, please
5724 <n8gray-AT-caltech.edu>. For all IPython-related requests, please
5321 contact Fernando.
5725 contact Fernando.
5322
5726
5323 As of early 2006, the following developers have joined the core team:
5727 As of early 2006, the following developers have joined the core team:
5324
5728
5325 * [Robert Kern] <rkern-AT-enthought.com>: co-mentored the 2005
5729 * [Robert Kern] <rkern-AT-enthought.com>: co-mentored the 2005
5326 Google Summer of Code project to develop python interactive
5730 Google Summer of Code project to develop python interactive
5327 notebooks (XML documents) and graphical interface. This project
5731 notebooks (XML documents) and graphical interface. This project
5328 was awarded to the students Tzanko Matev <tsanko-AT-gmail.com> and
5732 was awarded to the students Tzanko Matev <tsanko-AT-gmail.com> and
5329 Toni Alatalo <antont-AT-an.org>
5733 Toni Alatalo <antont-AT-an.org>
5330 * [Brian Granger] <bgranger-AT-scu.edu>: extending IPython to allow
5734 * [Brian Granger] <bgranger-AT-scu.edu>: extending IPython to allow
5331 support for interactive parallel computing.
5735 support for interactive parallel computing.
5332 * [Ville Vainio] <vivainio-AT-gmail.com>: Ville is the new
5736 * [Ville Vainio] <vivainio-AT-gmail.com>: Ville is the new
5333 maintainer for the main trunk of IPython after version 0.7.1.
5737 maintainer for the main trunk of IPython after version 0.7.1.
5334
5738
5335 User or development help should be requested via the IPython mailing lists:
5739 User or development help should be requested via the IPython mailing lists:
5336
5740
5337 *User list:*
5741 *User list:*
5338 http://scipy.net/mailman/listinfo/ipython-user
5742 http://scipy.net/mailman/listinfo/ipython-user
5339 *Developer's list:*
5743 *Developer's list:*
5340 http://scipy.net/mailman/listinfo/ipython-dev
5744 http://scipy.net/mailman/listinfo/ipython-dev
5341
5745
5342 The IPython project is also very grateful to^7 <footnode.html#foot2913>:
5746 The IPython project is also very grateful to:
5343
5747
5344 Bill Bumgarner <bbum-AT-friday.com>: for providing the DPyGetOpt module
5748 Bill Bumgarner <bbum-AT-friday.com>: for providing the DPyGetOpt module
5345 which gives very powerful and convenient handling of command-line
5749 which gives very powerful and convenient handling of command-line
5346 options (light years ahead of what Python 2.1.1's getopt module does).
5750 options (light years ahead of what Python 2.1.1's getopt module does).
5347
5751
5348 Ka-Ping Yee <ping-AT-lfw.org>: for providing the Itpl module for
5752 Ka-Ping Yee <ping-AT-lfw.org>: for providing the Itpl module for
5349 convenient and powerful string interpolation with a much nicer syntax
5753 convenient and powerful string interpolation with a much nicer syntax
5350 than formatting through the '%' operator.
5754 than formatting through the '%' operator.
5351
5755
5352 Arnd Baecker <baecker-AT-physik.tu-dresden.de>: for his many very useful
5756 Arnd Baecker <baecker-AT-physik.tu-dresden.de>: for his many very useful
5353 suggestions and comments, and lots of help with testing and
5757 suggestions and comments, and lots of help with testing and
5354 documentation checking. Many of IPython's newer features are a result of
5758 documentation checking. Many of IPython's newer features are a result of
5355 discussions with him (bugs are still my fault, not his).
5759 discussions with him (bugs are still my fault, not his).
5356
5760
5357 Obviously Guido van Rossum and the whole Python development team, that
5761 Obviously Guido van Rossum and the whole Python development team, that
5358 goes without saying.
5762 goes without saying.
5359
5763
5360 IPython's website is generously hosted at http://ipython.scipy.orgby
5764 IPython's website is generously hosted at http://ipython.scipy.orgby
5361 Enthought (http://www.enthought.com). I am very grateful to them and all
5765 Enthought (http://www.enthought.com). I am very grateful to them and all
5362 of the SciPy team for their contribution.
5766 of the SciPy team for their contribution.
5363
5767
5364 Fernando would also like to thank Stephen Figgins <fig-AT-monitor.net>,
5768 Fernando would also like to thank Stephen Figgins <fig-AT-monitor.net>,
5365 an O'Reilly Python editor. His Oct/11/2001 article about IPP and
5769 an O'Reilly Python editor. His Oct/11/2001 article about IPP and
5366 LazyPython, was what got this project started. You can read it at:
5770 LazyPython, was what got this project started. You can read it at:
5367 http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html.
5771 http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html.
5368
5772
5369 And last but not least, all the kind IPython users who have emailed new
5773 And last but not least, all the kind IPython users who have emailed new
5370 code, bug reports, fixes, comments and ideas. A brief list follows,
5774 code, bug reports, fixes, comments and ideas. A brief list follows,
5371 please let me know if I have ommitted your name by accident:
5775 please let me know if I have ommitted your name by accident:
5372
5776
5373 * [Jack Moffit] <jack-AT-xiph.org> Bug fixes, including the infamous
5777 * [Jack Moffit] <jack-AT-xiph.org> Bug fixes, including the infamous
5374 color problem. This bug alone caused many lost hours and
5778 color problem. This bug alone caused many lost hours and
5375 frustration, many thanks to him for the fix. I've always been a
5779 frustration, many thanks to him for the fix. I've always been a
5376 fan of Ogg & friends, now I have one more reason to like these folks.
5780 fan of Ogg & friends, now I have one more reason to like these folks.
5377 Jack is also contributing with Debian packaging and many other
5781 Jack is also contributing with Debian packaging and many other
5378 things.
5782 things.
5379 * [Alexander Schmolck] <a.schmolck-AT-gmx.net> Emacs work, bug
5783 * [Alexander Schmolck] <a.schmolck-AT-gmx.net> Emacs work, bug
5380 reports, bug fixes, ideas, lots more. The ipython.el mode for
5784 reports, bug fixes, ideas, lots more. The ipython.el mode for
5381 (X)Emacs is Alex's code, providing full support for IPython under
5785 (X)Emacs is Alex's code, providing full support for IPython under
5382 (X)Emacs.
5786 (X)Emacs.
5383 * [Andrea Riciputi] <andrea.riciputi-AT-libero.it> Mac OSX
5787 * [Andrea Riciputi] <andrea.riciputi-AT-libero.it> Mac OSX
5384 information, Fink package management.
5788 information, Fink package management.
5385 * [Gary Bishop] <gb-AT-cs.unc.edu> Bug reports, and patches to work
5789 * [Gary Bishop] <gb-AT-cs.unc.edu> Bug reports, and patches to work
5386 around the exception handling idiosyncracies of WxPython. Readline
5790 around the exception handling idiosyncracies of WxPython. Readline
5387 and color support for Windows.
5791 and color support for Windows.
5388 * [Jeffrey Collins] <Jeff.Collins-AT-vexcel.com> Bug reports. Much
5792 * [Jeffrey Collins] <Jeff.Collins-AT-vexcel.com> Bug reports. Much
5389 improved readline support, including fixes for Python 2.3.
5793 improved readline support, including fixes for Python 2.3.
5390 * [Dryice Liu] <dryice-AT-liu.com.cn> FreeBSD port.
5794 * [Dryice Liu] <dryice-AT-liu.com.cn> FreeBSD port.
5391 * [Mike Heeter] <korora-AT-SDF.LONESTAR.ORG>
5795 * [Mike Heeter] <korora-AT-SDF.LONESTAR.ORG>
5392 * [Christopher Hart] <hart-AT-caltech.edu> PDB integration.
5796 * [Christopher Hart] <hart-AT-caltech.edu> PDB integration.
5393 * [Milan Zamazal] <pdm-AT-zamazal.org> Emacs info.
5797 * [Milan Zamazal] <pdm-AT-zamazal.org> Emacs info.
5394 * [Philip Hisley] <compsys-AT-starpower.net>
5798 * [Philip Hisley] <compsys-AT-starpower.net>
5395 * [Holger Krekel] <pyth-AT-devel.trillke.net> Tab completion, lots
5799 * [Holger Krekel] <pyth-AT-devel.trillke.net> Tab completion, lots
5396 more.
5800 more.
5397 * [Robin Siebler] <robinsiebler-AT-starband.net>
5801 * [Robin Siebler] <robinsiebler-AT-starband.net>
5398 * [Ralf Ahlbrink] <ralf_ahlbrink-AT-web.de>
5802 * [Ralf Ahlbrink] <ralf_ahlbrink-AT-web.de>
5399 * [Thorsten Kampe] <thorsten-AT-thorstenkampe.de>
5803 * [Thorsten Kampe] <thorsten-AT-thorstenkampe.de>
5400 * [Fredrik Kant] <fredrik.kant-AT-front.com> Windows setup.
5804 * [Fredrik Kant] <fredrik.kant-AT-front.com> Windows setup.
5401 * [Syver Enstad] <syver-en-AT-online.no> Windows setup.
5805 * [Syver Enstad] <syver-en-AT-online.no> Windows setup.
5402 * [Richard] <rxe-AT-renre-europe.com> Global embedding.
5806 * [Richard] <rxe-AT-renre-europe.com> Global embedding.
5403 * [Hayden Callow] <h.callow-AT-elec.canterbury.ac.nz> Gnuplot.py 1.6
5807 * [Hayden Callow] <h.callow-AT-elec.canterbury.ac.nz> Gnuplot.py 1.6
5404 compatibility.
5808 compatibility.
5405 * [Leonardo Santagada] <retype-AT-terra.com.br> Fixes for Windows
5809 * [Leonardo Santagada] <retype-AT-terra.com.br> Fixes for Windows
5406 installation.
5810 installation.
5407 * [Christopher Armstrong] <radix-AT-twistedmatrix.com> Bugfixes.
5811 * [Christopher Armstrong] <radix-AT-twistedmatrix.com> Bugfixes.
5408 * [Francois Pinard] <pinard-AT-iro.umontreal.ca> Code and
5812 * [Francois Pinard] <pinard-AT-iro.umontreal.ca> Code and
5409 documentation fixes.
5813 documentation fixes.
5410 * [Cory Dodt] <cdodt-AT-fcoe.k12.ca.us> Bug reports and Windows
5814 * [Cory Dodt] <cdodt-AT-fcoe.k12.ca.us> Bug reports and Windows
5411 ideas. Patches for Windows installer.
5815 ideas. Patches for Windows installer.
5412 * [Olivier Aubert] <oaubert-AT-bat710.univ-lyon1.fr> New magics.
5816 * [Olivier Aubert] <oaubert-AT-bat710.univ-lyon1.fr> New magics.
5413 * [King C. Shu] <kingshu-AT-myrealbox.com> Autoindent patch.
5817 * [King C. Shu] <kingshu-AT-myrealbox.com> Autoindent patch.
5414 * [Chris Drexler] <chris-AT-ac-drexler.de> Readline packages for
5818 * [Chris Drexler] <chris-AT-ac-drexler.de> Readline packages for
5415 Win32/CygWin.
5819 Win32/CygWin.
5416 * [Gustavo Cordova Avila] <gcordova-AT-sismex.com> EvalDict code for
5820 * [Gustavo Cordova Avila] <gcordova-AT-sismex.com> EvalDict code for
5417 nice, lightweight string interpolation.
5821 nice, lightweight string interpolation.
5418 * [Kasper Souren] <Kasper.Souren-AT-ircam.fr> Bug reports, ideas.
5822 * [Kasper Souren] <Kasper.Souren-AT-ircam.fr> Bug reports, ideas.
5419 * [Gever Tulley] <gever-AT-helium.com> Code contributions.
5823 * [Gever Tulley] <gever-AT-helium.com> Code contributions.
5420 * [Ralf Schmitt] <ralf-AT-brainbot.com> Bug reports & fixes.
5824 * [Ralf Schmitt] <ralf-AT-brainbot.com> Bug reports & fixes.
5421 * [Oliver Sander] <osander-AT-gmx.de> Bug reports.
5825 * [Oliver Sander] <osander-AT-gmx.de> Bug reports.
5422 * [Rod Holland] <rhh-AT-structurelabs.com> Bug reports and fixes to
5826 * [Rod Holland] <rhh-AT-structurelabs.com> Bug reports and fixes to
5423 logging module.
5827 logging module.
5424 * [Daniel 'Dang' Griffith] <pythondev-dang-AT-lazytwinacres.net>
5828 * [Daniel 'Dang' Griffith] <pythondev-dang-AT-lazytwinacres.net>
5425 Fixes, enhancement suggestions for system shell use.
5829 Fixes, enhancement suggestions for system shell use.
5426 * [Viktor Ransmayr] <viktor.ransmayr-AT-t-online.de> Tests and
5830 * [Viktor Ransmayr] <viktor.ransmayr-AT-t-online.de> Tests and
5427 reports on Windows installation issues. Contributed a true Windows
5831 reports on Windows installation issues. Contributed a true Windows
5428 binary installer.
5832 binary installer.
5429 * [Mike Salib] <msalib-AT-mit.edu> Help fixing a subtle bug related
5833 * [Mike Salib] <msalib-AT-mit.edu> Help fixing a subtle bug related
5430 to traceback printing.
5834 to traceback printing.
5431 * [W.J. van der Laan] <gnufnork-AT-hetdigitalegat.nl> Bash-like
5835 * [W.J. van der Laan] <gnufnork-AT-hetdigitalegat.nl> Bash-like
5432 prompt specials.
5836 prompt specials.
5433 * [Antoon Pardon] <Antoon.Pardon-AT-rece.vub.ac.be> Critical fix for
5837 * [Antoon Pardon] <Antoon.Pardon-AT-rece.vub.ac.be> Critical fix for
5434 the multithreaded IPython.
5838 the multithreaded IPython.
5435 * [John Hunter] <jdhunter-AT-nitace.bsd.uchicago.edu> Matplotlib
5839 * [John Hunter] <jdhunter-AT-nitace.bsd.uchicago.edu> Matplotlib
5436 author, helped with all the development of support for matplotlib
5840 author, helped with all the development of support for matplotlib
5437 in IPyhton, including making necessary changes to matplotlib itself.
5841 in IPyhton, including making necessary changes to matplotlib itself.
5438 * [Matthew Arnison] <maffew-AT-cat.org.au> Bug reports, '%run -d' idea.
5842 * [Matthew Arnison] <maffew-AT-cat.org.au> Bug reports, '%run -d' idea.
5439 * [Prabhu Ramachandran] <prabhu_r-AT-users.sourceforge.net> Help
5843 * [Prabhu Ramachandran] <prabhu_r-AT-users.sourceforge.net> Help
5440 with (X)Emacs support, threading patches, ideas...
5844 with (X)Emacs support, threading patches, ideas...
5441 * [Norbert Tretkowski] <tretkowski-AT-inittab.de> help with Debian
5845 * [Norbert Tretkowski] <tretkowski-AT-inittab.de> help with Debian
5442 packaging and distribution.
5846 packaging and distribution.
5443 * [George Sakkis] <gsakkis-AT-eden.rutgers.edu> New matcher for
5847 * [George Sakkis] <gsakkis-AT-eden.rutgers.edu> New matcher for
5444 tab-completing named arguments of user-defined functions.
5848 tab-completing named arguments of user-defined functions.
5445 * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu> Wildcard
5849 * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu> Wildcard
5446 support implementation for searching namespaces.
5850 support implementation for searching namespaces.
5447 * [Vivian De Smedt] <vivian-AT-vdesmedt.com> Debugger enhancements,
5851 * [Vivian De Smedt] <vivian-AT-vdesmedt.com> Debugger enhancements,
5448 so that when pdb is activated from within IPython, coloring, tab
5852 so that when pdb is activated from within IPython, coloring, tab
5449 completion and other features continue to work seamlessly.
5853 completion and other features continue to work seamlessly.
5450 * [Scott Tsai] <scottt958-AT-yahoo.com.tw> Support for automatic
5854 * [Scott Tsai] <scottt958-AT-yahoo.com.tw> Support for automatic
5451 editor invocation on syntax errors (see
5855 editor invocation on syntax errors (see
5452 http://www.scipy.net/roundup/ipython/issue36).
5856 http://www.scipy.net/roundup/ipython/issue36).
5453 * [Alexander Belchenko] <bialix-AT-ukr.net> Improvements for win32
5857 * [Alexander Belchenko] <bialix-AT-ukr.net> Improvements for win32
5454 paging system.
5858 paging system.
5455 * [Will Maier] <willmaier-AT-ml1.net> Official OpenBSD port.
5859 * [Will Maier] <willmaier-AT-ml1.net> Official OpenBSD port.
5456
5860
General Comments 0
You need to be logged in to leave comments. Login now