##// END OF EJS Templates
- Fixes for doctest support. Need more testing, esp. to be sure they don't...
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,252 +1,62 b''
1 1 """ Legacy stuff
2 2
3 3 Various stuff that are there for historical / familiarity reasons.
4 4
5 5 This is automatically imported by default profile, though not other profiles
6 6 (e.g. 'sh' profile).
7 7
8 8 Stuff that is considered obsolete / redundant is gradually moved here.
9 9
10 10 """
11 11
12 12 import IPython.ipapi
13 13 ip = IPython.ipapi.get()
14 14
15 15 import os,sys
16 16
17 17 from IPython.genutils import *
18 18
19 # use ?
20 def magic_pdef(self, parameter_s='', namespaces=None):
21 """Print the definition header for any callable object.
22
23 If the object is a class, print the constructor information."""
24 self._inspect('pdef',parameter_s, namespaces)
25
26 ip.expose_magic("pdef", magic_pdef)
27
28 # use ?
29 def magic_pdoc(self, parameter_s='', namespaces=None):
30 """Print the docstring for an object.
31
32 If the given object is a class, it will print both the class and the
33 constructor docstrings."""
34 self._inspect('pdoc',parameter_s, namespaces)
35
36 ip.expose_magic("pdoc", magic_pdoc)
37
38 # use ??
39 def magic_psource(self, parameter_s='', namespaces=None):
40 """Print (or run through pager) the source code for an object."""
41 self._inspect('psource',parameter_s, namespaces)
42
43 ip.expose_magic("pdoc", magic_psource)
44
45 # use ?
46 def magic_pfile(self, parameter_s=''):
47 """Print (or run through pager) the file where an object is defined.
48
49 The file opens at the line where the object definition begins. IPython
50 will honor the environment variable PAGER if set, and otherwise will
51 do its best to print the file in a convenient form.
52
53 If the given argument is not an object currently defined, IPython will
54 try to interpret it as a filename (automatically adding a .py extension
55 if needed). You can thus use %pfile as a syntax highlighting code
56 viewer."""
57
58 # first interpret argument as an object name
59 out = self._inspect('pfile',parameter_s)
60 # if not, try the input as a filename
61 if out == 'not found':
62 try:
63 filename = get_py_filename(parameter_s)
64 except IOError,msg:
65 print msg
66 return
67 page(self.shell.inspector.format(file(filename).read()))
68
69 ip.expose_magic("pfile", magic_pfile)
70
71 19 # use rehashx
72 20
73 21 def magic_rehash(self, parameter_s = ''):
74 22 """Update the alias table with all entries in $PATH.
75 23
76 24 This version does no checks on execute permissions or whether the
77 25 contents of $PATH are truly files (instead of directories or something
78 26 else). For such a safer (but slower) version, use %rehashx."""
79 27
80 28 # This function (and rehashx) manipulate the alias_table directly
81 29 # rather than calling magic_alias, for speed reasons. A rehash on a
82 30 # typical Linux box involves several thousand entries, so efficiency
83 31 # here is a top concern.
84 32
85 33 path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep))
86 34 alias_table = self.shell.alias_table
87 35 for pdir in path:
88 36 for ff in os.listdir(pdir):
89 37 # each entry in the alias table must be (N,name), where
90 38 # N is the number of positional arguments of the alias.
91 39 alias_table[ff] = (0,ff)
92 40 # Make sure the alias table doesn't contain keywords or builtins
93 41 self.shell.alias_table_validate()
94 42 # Call again init_auto_alias() so we get 'rm -i' and other modified
95 43 # aliases since %rehash will probably clobber them
96 44 self.shell.init_auto_alias()
97 45
98 46 ip.expose_magic("rehash", magic_rehash)
99 47
100 #use cd -<tab>
101 def magic_dhist(self, parameter_s=''):
102 """Print your history of visited directories.
103
104 %dhist -> print full history\\
105 %dhist n -> print last n entries only\\
106 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
107
108 This history is automatically maintained by the %cd command, and
109 always available as the global list variable _dh. You can use %cd -<n>
110 to go to directory number <n>."""
111
112 dh = self.shell.user_ns['_dh']
113 if parameter_s:
114 try:
115 args = map(int,parameter_s.split())
116 except:
117 self.arg_err(Magic.magic_dhist)
118 return
119 if len(args) == 1:
120 ini,fin = max(len(dh)-(args[0]),0),len(dh)
121 elif len(args) == 2:
122 ini,fin = args
123 else:
124 self.arg_err(Magic.magic_dhist)
125 return
126 else:
127 ini,fin = 0,len(dh)
128 nlprint(dh,
129 header = 'Directory history (kept in _dh)',
130 start=ini,stop=fin)
131
132 ip.expose_magic("dhist", magic_dhist)
133
134 48 # Exit
135 49 def magic_Quit(self, parameter_s=''):
136 50 """Exit IPython without confirmation (like %Exit)."""
137 51
138 52 self.shell.exit_now = True
139 53
140 54 ip.expose_magic("Quit", magic_Quit)
141 55
142 56
143 57 # make it autocallable fn if you really need it
144 58 def magic_p(self, parameter_s=''):
145 59 """Just a short alias for Python's 'print'."""
146 60 exec 'print ' + parameter_s in self.shell.user_ns
147 61
148 62 ip.expose_magic("p", magic_p)
149
150 # up + enter. One char magic.
151 def magic_r(self, parameter_s=''):
152 """Repeat previous input.
153
154 If given an argument, repeats the previous command which starts with
155 the same string, otherwise it just repeats the previous input.
156
157 Shell escaped commands (with ! as first character) are not recognized
158 by this system, only pure python code and magic commands.
159 """
160
161 start = parameter_s.strip()
162 esc_magic = self.shell.ESC_MAGIC
163 # Identify magic commands even if automagic is on (which means
164 # the in-memory version is different from that typed by the user).
165 if self.shell.rc.automagic:
166 start_magic = esc_magic+start
167 else:
168 start_magic = start
169 # Look through the input history in reverse
170 for n in range(len(self.shell.input_hist)-2,0,-1):
171 input = self.shell.input_hist[n]
172 # skip plain 'r' lines so we don't recurse to infinity
173 if input != '_ip.magic("r")\n' and \
174 (input.startswith(start) or input.startswith(start_magic)):
175 #print 'match',`input` # dbg
176 print 'Executing:',input,
177 self.shell.runlines(input)
178 return
179 print 'No previous input matching `%s` found.' % start
180
181 ip.expose_magic("r", magic_r)
182
183
184 # use _ip.option.automagic
185
186 def magic_automagic(self, parameter_s = ''):
187 """Make magic functions callable without having to type the initial %.
188
189 Without argumentsl toggles on/off (when off, you must call it as
190 %automagic, of course). With arguments it sets the value, and you can
191 use any of (case insensitive):
192
193 - on,1,True: to activate
194
195 - off,0,False: to deactivate.
196
197 Note that magic functions have lowest priority, so if there's a
198 variable whose name collides with that of a magic fn, automagic won't
199 work for that function (you get the variable instead). However, if you
200 delete the variable (del var), the previously shadowed magic function
201 becomes visible to automagic again."""
202
203 rc = self.shell.rc
204 arg = parameter_s.lower()
205 if parameter_s in ('on','1','true'):
206 rc.automagic = True
207 elif parameter_s in ('off','0','false'):
208 rc.automagic = False
209 else:
210 rc.automagic = not rc.automagic
211 print '\n' + Magic.auto_status[rc.automagic]
212
213 ip.expose_magic("automagic", magic_automagic)
214
215 # use _ip.options.autocall
216 def magic_autocall(self, parameter_s = ''):
217 """Make functions callable without having to type parentheses.
218
219 Usage:
220
221 %autocall [mode]
222
223 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
224 value is toggled on and off (remembering the previous state)."""
225
226 rc = self.shell.rc
227
228 if parameter_s:
229 arg = int(parameter_s)
230 else:
231 arg = 'toggle'
232
233 if not arg in (0,1,2,'toggle'):
234 error('Valid modes: (0->Off, 1->Smart, 2->Full')
235 return
236
237 if arg in (0,1,2):
238 rc.autocall = arg
239 else: # toggle
240 if rc.autocall:
241 self._magic_state.autocall_save = rc.autocall
242 rc.autocall = 0
243 else:
244 try:
245 rc.autocall = self._magic_state.autocall_save
246 except AttributeError:
247 rc.autocall = self._magic_state.autocall_save = 1
248
249 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
250
251 ip.expose_magic("autocall", magic_autocall)
252
@@ -1,51 +1,52 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Class which mimics a module.
4 4
5 5 Needed to allow pickle to correctly resolve namespaces during IPython
6 6 sessions.
7 7
8 $Id: FakeModule.py 2169 2007-03-23 06:09:43Z fperez $"""
8 $Id: FakeModule.py 2723 2007-09-07 07:44:16Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 class FakeModule:
17 import types
18
19 class FakeModule(types.ModuleType):
18 20 """Simple class with attribute access to fake a module.
19 21
20 22 This is not meant to replace a module, but to allow inserting a fake
21 23 module in sys.modules so that systems which rely on run-time module
22 24 importing (like shelve and pickle) work correctly in interactive IPython
23 25 sessions.
24 26
25 27 Do NOT use this code for anything other than this IPython private hack."""
26
27 28 def __init__(self,adict):
28 29
29 30 # It seems pydoc (and perhaps others) needs any module instance to
30 31 # implement a __nonzero__ method, so we add it if missing:
31 32 if '__nonzero__' not in adict:
32 33 def __nonzero__():
33 34 return 1
34 35 adict['__nonzero__'] = __nonzero__
35 36
36 self.__dict__ = adict
37 self._dict_ = adict
37 38
38 39 # modules should have a __file__ attribute
39 40 adict.setdefault('__file__',__file__)
40 41
41 42 def __getattr__(self,key):
42 43 try:
43 return self.__dict__[key]
44 return self._dict_[key]
44 45 except KeyError, e:
45 46 raise AttributeError("FakeModule object has no attribute %s" % e)
46 47
47 48 def __str__(self):
48 49 return "<IPython.FakeModule instance>"
49 50
50 51 def __repr__(self):
51 52 return str(self)
@@ -1,3016 +1,3212 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 2705 2007-09-04 15:10:37Z vivainio $"""
4 $Id: Magic.py 2723 2007-09-07 07:44:16Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38 from sets import Set
39 39
40 40 # cProfile was added in Python2.5
41 41 try:
42 42 import cProfile as profile
43 43 import pstats
44 44 except ImportError:
45 45 # profile isn't bundled by default in Debian for license reasons
46 46 try:
47 47 import profile,pstats
48 48 except ImportError:
49 49 profile = pstats = None
50 50
51 51 # Homebrewed
52 52 import IPython
53 53 from IPython import Debugger, OInspect, wildcard
54 54 from IPython.FakeModule import FakeModule
55 55 from IPython.Itpl import Itpl, itpl, printpl,itplns
56 56 from IPython.PyColorize import Parser
57 57 from IPython.ipstruct import Struct
58 58 from IPython.macro import Macro
59 59 from IPython.genutils import *
60 60 from IPython import platutils
61 61 import IPython.generics
62 62 import IPython.ipapi
63 63
64 64 #***************************************************************************
65 65 # Utility functions
66 66 def on_off(tag):
67 67 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
68 68 return ['OFF','ON'][tag]
69 69
70 70 class Bunch: pass
71 71
72 72 def compress_dhist(dh):
73 73 head, tail = dh[:-10], dh[-10:]
74 74
75 75 newhead = []
76 76 done = Set()
77 77 for h in head:
78 78 if h in done:
79 79 continue
80 80 newhead.append(h)
81 81 done.add(h)
82 82
83 83 return newhead + tail
84 84
85 85
86 86 #***************************************************************************
87 87 # Main class implementing Magic functionality
88 88 class Magic:
89 89 """Magic functions for InteractiveShell.
90 90
91 91 Shell functions which can be reached as %function_name. All magic
92 92 functions should accept a string, which they can parse for their own
93 93 needs. This can make some functions easier to type, eg `%cd ../`
94 94 vs. `%cd("../")`
95 95
96 96 ALL definitions MUST begin with the prefix magic_. The user won't need it
97 97 at the command line, but it is is needed in the definition. """
98 98
99 99 # class globals
100 100 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
101 101 'Automagic is ON, % prefix NOT needed for magic functions.']
102 102
103 103 #......................................................................
104 104 # some utility functions
105 105
106 106 def __init__(self,shell):
107 107
108 108 self.options_table = {}
109 109 if profile is None:
110 110 self.magic_prun = self.profile_missing_notice
111 111 self.shell = shell
112 112
113 113 # namespace for holding state we may need
114 114 self._magic_state = Bunch()
115 115
116 116 def profile_missing_notice(self, *args, **kwargs):
117 117 error("""\
118 118 The profile module could not be found. If you are a Debian user,
119 119 it has been removed from the standard Debian package because of its non-free
120 120 license. To use profiling, please install"python2.3-profiler" from non-free.""")
121 121
122 122 def default_option(self,fn,optstr):
123 123 """Make an entry in the options_table for fn, with value optstr"""
124 124
125 125 if fn not in self.lsmagic():
126 126 error("%s is not a magic function" % fn)
127 127 self.options_table[fn] = optstr
128 128
129 129 def lsmagic(self):
130 130 """Return a list of currently available magic functions.
131 131
132 132 Gives a list of the bare names after mangling (['ls','cd', ...], not
133 133 ['magic_ls','magic_cd',...]"""
134 134
135 135 # FIXME. This needs a cleanup, in the way the magics list is built.
136 136
137 137 # magics in class definition
138 138 class_magic = lambda fn: fn.startswith('magic_') and \
139 139 callable(Magic.__dict__[fn])
140 140 # in instance namespace (run-time user additions)
141 141 inst_magic = lambda fn: fn.startswith('magic_') and \
142 142 callable(self.__dict__[fn])
143 143 # and bound magics by user (so they can access self):
144 144 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
145 145 callable(self.__class__.__dict__[fn])
146 146 magics = filter(class_magic,Magic.__dict__.keys()) + \
147 147 filter(inst_magic,self.__dict__.keys()) + \
148 148 filter(inst_bound_magic,self.__class__.__dict__.keys())
149 149 out = []
150 150 for fn in magics:
151 151 out.append(fn.replace('magic_','',1))
152 152 out.sort()
153 153 return out
154 154
155 155 def extract_input_slices(self,slices,raw=False):
156 156 """Return as a string a set of input history slices.
157 157
158 158 Inputs:
159 159
160 160 - slices: the set of slices is given as a list of strings (like
161 161 ['1','4:8','9'], since this function is for use by magic functions
162 162 which get their arguments as strings.
163 163
164 164 Optional inputs:
165 165
166 166 - raw(False): by default, the processed input is used. If this is
167 167 true, the raw input history is used instead.
168 168
169 169 Note that slices can be called with two notations:
170 170
171 171 N:M -> standard python form, means including items N...(M-1).
172 172
173 173 N-M -> include items N..M (closed endpoint)."""
174 174
175 175 if raw:
176 176 hist = self.shell.input_hist_raw
177 177 else:
178 178 hist = self.shell.input_hist
179 179
180 180 cmds = []
181 181 for chunk in slices:
182 182 if ':' in chunk:
183 183 ini,fin = map(int,chunk.split(':'))
184 184 elif '-' in chunk:
185 185 ini,fin = map(int,chunk.split('-'))
186 186 fin += 1
187 187 else:
188 188 ini = int(chunk)
189 189 fin = ini+1
190 190 cmds.append(hist[ini:fin])
191 191 return cmds
192 192
193 193 def _ofind(self, oname, namespaces=None):
194 194 """Find an object in the available namespaces.
195 195
196 196 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
197 197
198 198 Has special code to detect magic functions.
199 199 """
200 200
201 201 oname = oname.strip()
202 202
203 203 alias_ns = None
204 204 if namespaces is None:
205 205 # Namespaces to search in:
206 206 # Put them in a list. The order is important so that we
207 207 # find things in the same order that Python finds them.
208 208 namespaces = [ ('Interactive', self.shell.user_ns),
209 209 ('IPython internal', self.shell.internal_ns),
210 210 ('Python builtin', __builtin__.__dict__),
211 211 ('Alias', self.shell.alias_table),
212 212 ]
213 213 alias_ns = self.shell.alias_table
214 214
215 215 # initialize results to 'null'
216 216 found = 0; obj = None; ospace = None; ds = None;
217 217 ismagic = 0; isalias = 0; parent = None
218 218
219 219 # Look for the given name by splitting it in parts. If the head is
220 220 # found, then we look for all the remaining parts as members, and only
221 221 # declare success if we can find them all.
222 222 oname_parts = oname.split('.')
223 223 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
224 224 for nsname,ns in namespaces:
225 225 try:
226 226 obj = ns[oname_head]
227 227 except KeyError:
228 228 continue
229 229 else:
230 230 #print 'oname_rest:', oname_rest # dbg
231 231 for part in oname_rest:
232 232 try:
233 233 parent = obj
234 234 obj = getattr(obj,part)
235 235 except:
236 236 # Blanket except b/c some badly implemented objects
237 237 # allow __getattr__ to raise exceptions other than
238 238 # AttributeError, which then crashes IPython.
239 239 break
240 240 else:
241 241 # If we finish the for loop (no break), we got all members
242 242 found = 1
243 243 ospace = nsname
244 244 if ns == alias_ns:
245 245 isalias = 1
246 246 break # namespace loop
247 247
248 248 # Try to see if it's magic
249 249 if not found:
250 250 if oname.startswith(self.shell.ESC_MAGIC):
251 251 oname = oname[1:]
252 252 obj = getattr(self,'magic_'+oname,None)
253 253 if obj is not None:
254 254 found = 1
255 255 ospace = 'IPython internal'
256 256 ismagic = 1
257 257
258 258 # Last try: special-case some literals like '', [], {}, etc:
259 259 if not found and oname_head in ["''",'""','[]','{}','()']:
260 260 obj = eval(oname_head)
261 261 found = 1
262 262 ospace = 'Interactive'
263 263
264 264 return {'found':found, 'obj':obj, 'namespace':ospace,
265 265 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
266 266
267 267 def arg_err(self,func):
268 268 """Print docstring if incorrect arguments were passed"""
269 269 print 'Error in arguments:'
270 270 print OInspect.getdoc(func)
271 271
272 272 def format_latex(self,strng):
273 273 """Format a string for latex inclusion."""
274 274
275 275 # Characters that need to be escaped for latex:
276 276 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
277 277 # Magic command names as headers:
278 278 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
279 279 re.MULTILINE)
280 280 # Magic commands
281 281 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
282 282 re.MULTILINE)
283 283 # Paragraph continue
284 284 par_re = re.compile(r'\\$',re.MULTILINE)
285 285
286 286 # The "\n" symbol
287 287 newline_re = re.compile(r'\\n')
288 288
289 289 # Now build the string for output:
290 290 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
291 291 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
292 292 strng)
293 293 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
294 294 strng = par_re.sub(r'\\\\',strng)
295 295 strng = escape_re.sub(r'\\\1',strng)
296 296 strng = newline_re.sub(r'\\textbackslash{}n',strng)
297 297 return strng
298 298
299 299 def format_screen(self,strng):
300 300 """Format a string for screen printing.
301 301
302 302 This removes some latex-type format codes."""
303 303 # Paragraph continue
304 304 par_re = re.compile(r'\\$',re.MULTILINE)
305 305 strng = par_re.sub('',strng)
306 306 return strng
307 307
308 308 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
309 309 """Parse options passed to an argument string.
310 310
311 311 The interface is similar to that of getopt(), but it returns back a
312 312 Struct with the options as keys and the stripped argument string still
313 313 as a string.
314 314
315 315 arg_str is quoted as a true sys.argv vector by using shlex.split.
316 316 This allows us to easily expand variables, glob files, quote
317 317 arguments, etc.
318 318
319 319 Options:
320 320 -mode: default 'string'. If given as 'list', the argument string is
321 321 returned as a list (split on whitespace) instead of a string.
322 322
323 323 -list_all: put all option values in lists. Normally only options
324 324 appearing more than once are put in a list.
325 325
326 326 -posix (True): whether to split the input line in POSIX mode or not,
327 327 as per the conventions outlined in the shlex module from the
328 328 standard library."""
329 329
330 330 # inject default options at the beginning of the input line
331 331 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
332 332 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
333 333
334 334 mode = kw.get('mode','string')
335 335 if mode not in ['string','list']:
336 336 raise ValueError,'incorrect mode given: %s' % mode
337 337 # Get options
338 338 list_all = kw.get('list_all',0)
339 339 posix = kw.get('posix',True)
340 340
341 341 # Check if we have more than one argument to warrant extra processing:
342 342 odict = {} # Dictionary with options
343 343 args = arg_str.split()
344 344 if len(args) >= 1:
345 345 # If the list of inputs only has 0 or 1 thing in it, there's no
346 346 # need to look for options
347 347 argv = arg_split(arg_str,posix)
348 348 # Do regular option processing
349 349 try:
350 350 opts,args = getopt(argv,opt_str,*long_opts)
351 351 except GetoptError,e:
352 352 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
353 353 " ".join(long_opts)))
354 354 for o,a in opts:
355 355 if o.startswith('--'):
356 356 o = o[2:]
357 357 else:
358 358 o = o[1:]
359 359 try:
360 360 odict[o].append(a)
361 361 except AttributeError:
362 362 odict[o] = [odict[o],a]
363 363 except KeyError:
364 364 if list_all:
365 365 odict[o] = [a]
366 366 else:
367 367 odict[o] = a
368 368
369 369 # Prepare opts,args for return
370 370 opts = Struct(odict)
371 371 if mode == 'string':
372 372 args = ' '.join(args)
373 373
374 374 return opts,args
375 375
376 376 #......................................................................
377 377 # And now the actual magic functions
378 378
379 379 # Functions for IPython shell work (vars,funcs, config, etc)
380 380 def magic_lsmagic(self, parameter_s = ''):
381 381 """List currently available magic functions."""
382 382 mesc = self.shell.ESC_MAGIC
383 383 print 'Available magic functions:\n'+mesc+\
384 384 (' '+mesc).join(self.lsmagic())
385 385 print '\n' + Magic.auto_status[self.shell.rc.automagic]
386 386 return None
387 387
388 388 def magic_magic(self, parameter_s = ''):
389 389 """Print information about the magic function system."""
390 390
391 391 mode = ''
392 392 try:
393 393 if parameter_s.split()[0] == '-latex':
394 394 mode = 'latex'
395 395 if parameter_s.split()[0] == '-brief':
396 396 mode = 'brief'
397 397 except:
398 398 pass
399 399
400 400 magic_docs = []
401 401 for fname in self.lsmagic():
402 402 mname = 'magic_' + fname
403 403 for space in (Magic,self,self.__class__):
404 404 try:
405 405 fn = space.__dict__[mname]
406 406 except KeyError:
407 407 pass
408 408 else:
409 409 break
410 410 if mode == 'brief':
411 411 # only first line
412 412 fndoc = fn.__doc__.split('\n',1)[0]
413 413 else:
414 414 fndoc = fn.__doc__
415 415
416 416 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
417 417 fname,fndoc))
418 418 magic_docs = ''.join(magic_docs)
419 419
420 420 if mode == 'latex':
421 421 print self.format_latex(magic_docs)
422 422 return
423 423 else:
424 424 magic_docs = self.format_screen(magic_docs)
425 425 if mode == 'brief':
426 426 return magic_docs
427 427
428 428 outmsg = """
429 429 IPython's 'magic' functions
430 430 ===========================
431 431
432 432 The magic function system provides a series of functions which allow you to
433 433 control the behavior of IPython itself, plus a lot of system-type
434 434 features. All these functions are prefixed with a % character, but parameters
435 435 are given without parentheses or quotes.
436 436
437 437 NOTE: If you have 'automagic' enabled (via the command line option or with the
438 438 %automagic function), you don't need to type in the % explicitly. By default,
439 439 IPython ships with automagic on, so you should only rarely need the % escape.
440 440
441 441 Example: typing '%cd mydir' (without the quotes) changes you working directory
442 442 to 'mydir', if it exists.
443 443
444 444 You can define your own magic functions to extend the system. See the supplied
445 445 ipythonrc and example-magic.py files for details (in your ipython
446 446 configuration directory, typically $HOME/.ipython/).
447 447
448 448 You can also define your own aliased names for magic functions. In your
449 449 ipythonrc file, placing a line like:
450 450
451 451 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
452 452
453 453 will define %pf as a new name for %profile.
454 454
455 455 You can also call magics in code using the ipmagic() function, which IPython
456 456 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
457 457
458 458 For a list of the available magic functions, use %lsmagic. For a description
459 459 of any of them, type %magic_name?, e.g. '%cd?'.
460 460
461 461 Currently the magic system has the following functions:\n"""
462 462
463 463 mesc = self.shell.ESC_MAGIC
464 464 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
465 465 "\n\n%s%s\n\n%s" % (outmsg,
466 466 magic_docs,mesc,mesc,
467 467 (' '+mesc).join(self.lsmagic()),
468 468 Magic.auto_status[self.shell.rc.automagic] ) )
469 469
470 470 page(outmsg,screen_lines=self.shell.rc.screen_length)
471 471
472 472
473 473 def magic_autoindent(self, parameter_s = ''):
474 474 """Toggle autoindent on/off (if available)."""
475 475
476 476 self.shell.set_autoindent()
477 477 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
478 478
479
480 def magic_automagic(self, parameter_s = ''):
481 """Make magic functions callable without having to type the initial %.
482
483 Without argumentsl toggles on/off (when off, you must call it as
484 %automagic, of course). With arguments it sets the value, and you can
485 use any of (case insensitive):
486
487 - on,1,True: to activate
488
489 - off,0,False: to deactivate.
490
491 Note that magic functions have lowest priority, so if there's a
492 variable whose name collides with that of a magic fn, automagic won't
493 work for that function (you get the variable instead). However, if you
494 delete the variable (del var), the previously shadowed magic function
495 becomes visible to automagic again."""
496
497 rc = self.shell.rc
498 arg = parameter_s.lower()
499 if parameter_s in ('on','1','true'):
500 rc.automagic = True
501 elif parameter_s in ('off','0','false'):
502 rc.automagic = False
503 else:
504 rc.automagic = not rc.automagic
505 print '\n' + Magic.auto_status[rc.automagic]
506
507
508 def magic_autocall(self, parameter_s = ''):
509 """Make functions callable without having to type parentheses.
510
511 Usage:
512
513 %autocall [mode]
514
515 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
516 value is toggled on and off (remembering the previous state).
517
518 In more detail, these values mean:
519
520 0 -> fully disabled
521
522 1 -> active, but do not apply if there are no arguments on the line.
523
524 In this mode, you get:
525
526 In [1]: callable
527 Out[1]: <built-in function callable>
528
529 In [2]: callable 'hello'
530 ------> callable('hello')
531 Out[2]: False
532
533 2 -> Active always. Even if no arguments are present, the callable
534 object is called:
535
536 In [4]: callable
537 ------> callable()
538
539 Note that even with autocall off, you can still use '/' at the start of
540 a line to treat the first argument on the command line as a function
541 and add parentheses to it:
542
543 In [8]: /str 43
544 ------> str(43)
545 Out[8]: '43'
546 """
547
548 rc = self.shell.rc
549
550 if parameter_s:
551 arg = int(parameter_s)
552 else:
553 arg = 'toggle'
554
555 if not arg in (0,1,2,'toggle'):
556 error('Valid modes: (0->Off, 1->Smart, 2->Full')
557 return
558
559 if arg in (0,1,2):
560 rc.autocall = arg
561 else: # toggle
562 if rc.autocall:
563 self._magic_state.autocall_save = rc.autocall
564 rc.autocall = 0
565 else:
566 try:
567 rc.autocall = self._magic_state.autocall_save
568 except AttributeError:
569 rc.autocall = self._magic_state.autocall_save = 1
570
571 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
572
479 573 def magic_system_verbose(self, parameter_s = ''):
480 574 """Set verbose printing of system calls.
481 575
482 576 If called without an argument, act as a toggle"""
483 577
484 578 if parameter_s:
485 579 val = bool(eval(parameter_s))
486 580 else:
487 581 val = None
488 582
489 583 self.shell.rc_set_toggle('system_verbose',val)
490 584 print "System verbose printing is:",\
491 585 ['OFF','ON'][self.shell.rc.system_verbose]
492 586
493 587
494 588 def magic_page(self, parameter_s=''):
495 589 """Pretty print the object and display it through a pager.
496 590
497 591 %page [options] OBJECT
498 592
499 593 If no object is given, use _ (last output).
500 594
501 595 Options:
502 596
503 597 -r: page str(object), don't pretty-print it."""
504 598
505 599 # After a function contributed by Olivier Aubert, slightly modified.
506 600
507 601 # Process options/args
508 602 opts,args = self.parse_options(parameter_s,'r')
509 603 raw = 'r' in opts
510 604
511 605 oname = args and args or '_'
512 606 info = self._ofind(oname)
513 607 if info['found']:
514 608 txt = (raw and str or pformat)( info['obj'] )
515 609 page(txt)
516 610 else:
517 611 print 'Object `%s` not found' % oname
518 612
519 613 def magic_profile(self, parameter_s=''):
520 614 """Print your currently active IPyhton profile."""
521 615 if self.shell.rc.profile:
522 616 printpl('Current IPython profile: $self.shell.rc.profile.')
523 617 else:
524 618 print 'No profile active.'
525 619
526 620 def magic_pinfo(self, parameter_s='', namespaces=None):
527 621 """Provide detailed information about an object.
528 622
529 623 '%pinfo object' is just a synonym for object? or ?object."""
530 624
531 625 #print 'pinfo par: <%s>' % parameter_s # dbg
532 626
533 627
534 628 # detail_level: 0 -> obj? , 1 -> obj??
535 629 detail_level = 0
536 630 # We need to detect if we got called as 'pinfo pinfo foo', which can
537 631 # happen if the user types 'pinfo foo?' at the cmd line.
538 632 pinfo,qmark1,oname,qmark2 = \
539 633 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
540 634 if pinfo or qmark1 or qmark2:
541 635 detail_level = 1
542 636 if "*" in oname:
543 637 self.magic_psearch(oname)
544 638 else:
545 639 self._inspect('pinfo', oname, detail_level=detail_level,
546 640 namespaces=namespaces)
547
641
642 def magic_pdef(self, parameter_s='', namespaces=None):
643 """Print the definition header for any callable object.
644
645 If the object is a class, print the constructor information."""
646 self._inspect('pdef',parameter_s, namespaces)
647
648 def magic_pdoc(self, parameter_s='', namespaces=None):
649 """Print the docstring for an object.
650
651 If the given object is a class, it will print both the class and the
652 constructor docstrings."""
653 self._inspect('pdoc',parameter_s, namespaces)
654
655 def magic_psource(self, parameter_s='', namespaces=None):
656 """Print (or run through pager) the source code for an object."""
657 self._inspect('psource',parameter_s, namespaces)
658
659 def magic_pfile(self, parameter_s=''):
660 """Print (or run through pager) the file where an object is defined.
661
662 The file opens at the line where the object definition begins. IPython
663 will honor the environment variable PAGER if set, and otherwise will
664 do its best to print the file in a convenient form.
665
666 If the given argument is not an object currently defined, IPython will
667 try to interpret it as a filename (automatically adding a .py extension
668 if needed). You can thus use %pfile as a syntax highlighting code
669 viewer."""
670
671 # first interpret argument as an object name
672 out = self._inspect('pfile',parameter_s)
673 # if not, try the input as a filename
674 if out == 'not found':
675 try:
676 filename = get_py_filename(parameter_s)
677 except IOError,msg:
678 print msg
679 return
680 page(self.shell.inspector.format(file(filename).read()))
681
548 682 def _inspect(self,meth,oname,namespaces=None,**kw):
549 683 """Generic interface to the inspector system.
550 684
551 685 This function is meant to be called by pdef, pdoc & friends."""
552 686
553 687 #oname = oname.strip()
554 688 #print '1- oname: <%r>' % oname # dbg
555 689 try:
556 690 oname = oname.strip().encode('ascii')
557 691 #print '2- oname: <%r>' % oname # dbg
558 692 except UnicodeEncodeError:
559 693 print 'Python identifiers can only contain ascii characters.'
560 694 return 'not found'
561 695
562 696 info = Struct(self._ofind(oname, namespaces))
563 697
564 698 if info.found:
565 699 try:
566 700 IPython.generics.inspect_object(info.obj)
567 701 return
568 702 except IPython.ipapi.TryNext:
569 703 pass
570 704 # Get the docstring of the class property if it exists.
571 705 path = oname.split('.')
572 706 root = '.'.join(path[:-1])
573 707 if info.parent is not None:
574 708 try:
575 709 target = getattr(info.parent, '__class__')
576 710 # The object belongs to a class instance.
577 711 try:
578 712 target = getattr(target, path[-1])
579 713 # The class defines the object.
580 714 if isinstance(target, property):
581 715 oname = root + '.__class__.' + path[-1]
582 716 info = Struct(self._ofind(oname))
583 717 except AttributeError: pass
584 718 except AttributeError: pass
585 719
586 720 pmethod = getattr(self.shell.inspector,meth)
587 721 formatter = info.ismagic and self.format_screen or None
588 722 if meth == 'pdoc':
589 723 pmethod(info.obj,oname,formatter)
590 724 elif meth == 'pinfo':
591 725 pmethod(info.obj,oname,formatter,info,**kw)
592 726 else:
593 727 pmethod(info.obj,oname)
594 728 else:
595 729 print 'Object `%s` not found.' % oname
596 730 return 'not found' # so callers can take other action
597 731
598 732 def magic_psearch(self, parameter_s=''):
599 733 """Search for object in namespaces by wildcard.
600 734
601 735 %psearch [options] PATTERN [OBJECT TYPE]
602 736
603 737 Note: ? can be used as a synonym for %psearch, at the beginning or at
604 738 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
605 739 rest of the command line must be unchanged (options come first), so
606 740 for example the following forms are equivalent
607 741
608 742 %psearch -i a* function
609 743 -i a* function?
610 744 ?-i a* function
611 745
612 746 Arguments:
613 747
614 748 PATTERN
615 749
616 750 where PATTERN is a string containing * as a wildcard similar to its
617 751 use in a shell. The pattern is matched in all namespaces on the
618 752 search path. By default objects starting with a single _ are not
619 753 matched, many IPython generated objects have a single
620 754 underscore. The default is case insensitive matching. Matching is
621 755 also done on the attributes of objects and not only on the objects
622 756 in a module.
623 757
624 758 [OBJECT TYPE]
625 759
626 760 Is the name of a python type from the types module. The name is
627 761 given in lowercase without the ending type, ex. StringType is
628 762 written string. By adding a type here only objects matching the
629 763 given type are matched. Using all here makes the pattern match all
630 764 types (this is the default).
631 765
632 766 Options:
633 767
634 768 -a: makes the pattern match even objects whose names start with a
635 769 single underscore. These names are normally ommitted from the
636 770 search.
637 771
638 772 -i/-c: make the pattern case insensitive/sensitive. If neither of
639 773 these options is given, the default is read from your ipythonrc
640 774 file. The option name which sets this value is
641 775 'wildcards_case_sensitive'. If this option is not specified in your
642 776 ipythonrc file, IPython's internal default is to do a case sensitive
643 777 search.
644 778
645 779 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
646 780 specifiy can be searched in any of the following namespaces:
647 781 'builtin', 'user', 'user_global','internal', 'alias', where
648 782 'builtin' and 'user' are the search defaults. Note that you should
649 783 not use quotes when specifying namespaces.
650 784
651 785 'Builtin' contains the python module builtin, 'user' contains all
652 786 user data, 'alias' only contain the shell aliases and no python
653 787 objects, 'internal' contains objects used by IPython. The
654 788 'user_global' namespace is only used by embedded IPython instances,
655 789 and it contains module-level globals. You can add namespaces to the
656 790 search with -s or exclude them with -e (these options can be given
657 791 more than once).
658 792
659 793 Examples:
660 794
661 795 %psearch a* -> objects beginning with an a
662 796 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
663 797 %psearch a* function -> all functions beginning with an a
664 798 %psearch re.e* -> objects beginning with an e in module re
665 799 %psearch r*.e* -> objects that start with e in modules starting in r
666 800 %psearch r*.* string -> all strings in modules beginning with r
667 801
668 802 Case sensitve search:
669 803
670 804 %psearch -c a* list all object beginning with lower case a
671 805
672 806 Show objects beginning with a single _:
673 807
674 808 %psearch -a _* list objects beginning with a single underscore"""
675 809 try:
676 810 parameter_s = parameter_s.encode('ascii')
677 811 except UnicodeEncodeError:
678 812 print 'Python identifiers can only contain ascii characters.'
679 813 return
680 814
681 815 # default namespaces to be searched
682 816 def_search = ['user','builtin']
683 817
684 818 # Process options/args
685 819 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
686 820 opt = opts.get
687 821 shell = self.shell
688 822 psearch = shell.inspector.psearch
689 823
690 824 # select case options
691 825 if opts.has_key('i'):
692 826 ignore_case = True
693 827 elif opts.has_key('c'):
694 828 ignore_case = False
695 829 else:
696 830 ignore_case = not shell.rc.wildcards_case_sensitive
697 831
698 832 # Build list of namespaces to search from user options
699 833 def_search.extend(opt('s',[]))
700 834 ns_exclude = ns_exclude=opt('e',[])
701 835 ns_search = [nm for nm in def_search if nm not in ns_exclude]
702 836
703 837 # Call the actual search
704 838 try:
705 839 psearch(args,shell.ns_table,ns_search,
706 840 show_all=opt('a'),ignore_case=ignore_case)
707 841 except:
708 842 shell.showtraceback()
709 843
710 844 def magic_who_ls(self, parameter_s=''):
711 845 """Return a sorted list of all interactive variables.
712 846
713 847 If arguments are given, only variables of types matching these
714 848 arguments are returned."""
715 849
716 850 user_ns = self.shell.user_ns
717 851 internal_ns = self.shell.internal_ns
718 852 user_config_ns = self.shell.user_config_ns
719 853 out = []
720 854 typelist = parameter_s.split()
721 855
722 856 for i in user_ns:
723 857 if not (i.startswith('_') or i.startswith('_i')) \
724 858 and not (i in internal_ns or i in user_config_ns):
725 859 if typelist:
726 860 if type(user_ns[i]).__name__ in typelist:
727 861 out.append(i)
728 862 else:
729 863 out.append(i)
730 864 out.sort()
731 865 return out
732 866
733 867 def magic_who(self, parameter_s=''):
734 868 """Print all interactive variables, with some minimal formatting.
735 869
736 870 If any arguments are given, only variables whose type matches one of
737 871 these are printed. For example:
738 872
739 873 %who function str
740 874
741 875 will only list functions and strings, excluding all other types of
742 876 variables. To find the proper type names, simply use type(var) at a
743 877 command line to see how python prints type names. For example:
744 878
745 879 In [1]: type('hello')\\
746 880 Out[1]: <type 'str'>
747 881
748 882 indicates that the type name for strings is 'str'.
749 883
750 884 %who always excludes executed names loaded through your configuration
751 885 file and things which are internal to IPython.
752 886
753 887 This is deliberate, as typically you may load many modules and the
754 888 purpose of %who is to show you only what you've manually defined."""
755 889
756 890 varlist = self.magic_who_ls(parameter_s)
757 891 if not varlist:
758 892 if parameter_s:
759 893 print 'No variables match your requested type.'
760 894 else:
761 895 print 'Interactive namespace is empty.'
762 896 return
763 897
764 898 # if we have variables, move on...
765 899 count = 0
766 900 for i in varlist:
767 901 print i+'\t',
768 902 count += 1
769 903 if count > 8:
770 904 count = 0
771 905 print
772 906 print
773 907
774 908 def magic_whos(self, parameter_s=''):
775 909 """Like %who, but gives some extra information about each variable.
776 910
777 911 The same type filtering of %who can be applied here.
778 912
779 913 For all variables, the type is printed. Additionally it prints:
780 914
781 915 - For {},[],(): their length.
782 916
783 917 - For numpy and Numeric arrays, a summary with shape, number of
784 918 elements, typecode and size in memory.
785 919
786 920 - Everything else: a string representation, snipping their middle if
787 921 too long."""
788 922
789 923 varnames = self.magic_who_ls(parameter_s)
790 924 if not varnames:
791 925 if parameter_s:
792 926 print 'No variables match your requested type.'
793 927 else:
794 928 print 'Interactive namespace is empty.'
795 929 return
796 930
797 931 # if we have variables, move on...
798 932
799 933 # for these types, show len() instead of data:
800 934 seq_types = [types.DictType,types.ListType,types.TupleType]
801 935
802 936 # for numpy/Numeric arrays, display summary info
803 937 try:
804 938 import numpy
805 939 except ImportError:
806 940 ndarray_type = None
807 941 else:
808 942 ndarray_type = numpy.ndarray.__name__
809 943 try:
810 944 import Numeric
811 945 except ImportError:
812 946 array_type = None
813 947 else:
814 948 array_type = Numeric.ArrayType.__name__
815 949
816 950 # Find all variable names and types so we can figure out column sizes
817 951 def get_vars(i):
818 952 return self.shell.user_ns[i]
819 953
820 954 # some types are well known and can be shorter
821 955 abbrevs = {'IPython.macro.Macro' : 'Macro'}
822 956 def type_name(v):
823 957 tn = type(v).__name__
824 958 return abbrevs.get(tn,tn)
825 959
826 960 varlist = map(get_vars,varnames)
827 961
828 962 typelist = []
829 963 for vv in varlist:
830 964 tt = type_name(vv)
831 965
832 966 if tt=='instance':
833 967 typelist.append( abbrevs.get(str(vv.__class__),
834 968 str(vv.__class__)))
835 969 else:
836 970 typelist.append(tt)
837 971
838 972 # column labels and # of spaces as separator
839 973 varlabel = 'Variable'
840 974 typelabel = 'Type'
841 975 datalabel = 'Data/Info'
842 976 colsep = 3
843 977 # variable format strings
844 978 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
845 979 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
846 980 aformat = "%s: %s elems, type `%s`, %s bytes"
847 981 # find the size of the columns to format the output nicely
848 982 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
849 983 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
850 984 # table header
851 985 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
852 986 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
853 987 # and the table itself
854 988 kb = 1024
855 989 Mb = 1048576 # kb**2
856 990 for vname,var,vtype in zip(varnames,varlist,typelist):
857 991 print itpl(vformat),
858 992 if vtype in seq_types:
859 993 print len(var)
860 994 elif vtype in [array_type,ndarray_type]:
861 995 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
862 996 if vtype==ndarray_type:
863 997 # numpy
864 998 vsize = var.size
865 999 vbytes = vsize*var.itemsize
866 1000 vdtype = var.dtype
867 1001 else:
868 1002 # Numeric
869 1003 vsize = Numeric.size(var)
870 1004 vbytes = vsize*var.itemsize()
871 1005 vdtype = var.typecode()
872 1006
873 1007 if vbytes < 100000:
874 1008 print aformat % (vshape,vsize,vdtype,vbytes)
875 1009 else:
876 1010 print aformat % (vshape,vsize,vdtype,vbytes),
877 1011 if vbytes < Mb:
878 1012 print '(%s kb)' % (vbytes/kb,)
879 1013 else:
880 1014 print '(%s Mb)' % (vbytes/Mb,)
881 1015 else:
882 1016 try:
883 1017 vstr = str(var)
884 1018 except UnicodeEncodeError:
885 1019 vstr = unicode(var).encode(sys.getdefaultencoding(),
886 1020 'backslashreplace')
887 1021 vstr = vstr.replace('\n','\\n')
888 1022 if len(vstr) < 50:
889 1023 print vstr
890 1024 else:
891 1025 printpl(vfmt_short)
892 1026
893 1027 def magic_reset(self, parameter_s=''):
894 1028 """Resets the namespace by removing all names defined by the user.
895 1029
896 1030 Input/Output history are left around in case you need them."""
897 1031
898 1032 ans = self.shell.ask_yes_no(
899 1033 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
900 1034 if not ans:
901 1035 print 'Nothing done.'
902 1036 return
903 1037 user_ns = self.shell.user_ns
904 1038 for i in self.magic_who_ls():
905 1039 del(user_ns[i])
906 1040
907 1041 def magic_logstart(self,parameter_s=''):
908 1042 """Start logging anywhere in a session.
909 1043
910 1044 %logstart [-o|-r|-t] [log_name [log_mode]]
911 1045
912 1046 If no name is given, it defaults to a file named 'ipython_log.py' in your
913 1047 current directory, in 'rotate' mode (see below).
914 1048
915 1049 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
916 1050 history up to that point and then continues logging.
917 1051
918 1052 %logstart takes a second optional parameter: logging mode. This can be one
919 1053 of (note that the modes are given unquoted):\\
920 1054 append: well, that says it.\\
921 1055 backup: rename (if exists) to name~ and start name.\\
922 1056 global: single logfile in your home dir, appended to.\\
923 1057 over : overwrite existing log.\\
924 1058 rotate: create rotating logs name.1~, name.2~, etc.
925 1059
926 1060 Options:
927 1061
928 1062 -o: log also IPython's output. In this mode, all commands which
929 1063 generate an Out[NN] prompt are recorded to the logfile, right after
930 1064 their corresponding input line. The output lines are always
931 1065 prepended with a '#[Out]# ' marker, so that the log remains valid
932 1066 Python code.
933 1067
934 1068 Since this marker is always the same, filtering only the output from
935 1069 a log is very easy, using for example a simple awk call:
936 1070
937 1071 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
938 1072
939 1073 -r: log 'raw' input. Normally, IPython's logs contain the processed
940 1074 input, so that user lines are logged in their final form, converted
941 1075 into valid Python. For example, %Exit is logged as
942 1076 '_ip.magic("Exit"). If the -r flag is given, all input is logged
943 1077 exactly as typed, with no transformations applied.
944 1078
945 1079 -t: put timestamps before each input line logged (these are put in
946 1080 comments)."""
947 1081
948 1082 opts,par = self.parse_options(parameter_s,'ort')
949 1083 log_output = 'o' in opts
950 1084 log_raw_input = 'r' in opts
951 1085 timestamp = 't' in opts
952 1086
953 1087 rc = self.shell.rc
954 1088 logger = self.shell.logger
955 1089
956 1090 # if no args are given, the defaults set in the logger constructor by
957 1091 # ipytohn remain valid
958 1092 if par:
959 1093 try:
960 1094 logfname,logmode = par.split()
961 1095 except:
962 1096 logfname = par
963 1097 logmode = 'backup'
964 1098 else:
965 1099 logfname = logger.logfname
966 1100 logmode = logger.logmode
967 1101 # put logfname into rc struct as if it had been called on the command
968 1102 # line, so it ends up saved in the log header Save it in case we need
969 1103 # to restore it...
970 1104 old_logfile = rc.opts.get('logfile','')
971 1105 if logfname:
972 1106 logfname = os.path.expanduser(logfname)
973 1107 rc.opts.logfile = logfname
974 1108 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
975 1109 try:
976 1110 started = logger.logstart(logfname,loghead,logmode,
977 1111 log_output,timestamp,log_raw_input)
978 1112 except:
979 1113 rc.opts.logfile = old_logfile
980 1114 warn("Couldn't start log: %s" % sys.exc_info()[1])
981 1115 else:
982 1116 # log input history up to this point, optionally interleaving
983 1117 # output if requested
984 1118
985 1119 if timestamp:
986 1120 # disable timestamping for the previous history, since we've
987 1121 # lost those already (no time machine here).
988 1122 logger.timestamp = False
989 1123
990 1124 if log_raw_input:
991 1125 input_hist = self.shell.input_hist_raw
992 1126 else:
993 1127 input_hist = self.shell.input_hist
994 1128
995 1129 if log_output:
996 1130 log_write = logger.log_write
997 1131 output_hist = self.shell.output_hist
998 1132 for n in range(1,len(input_hist)-1):
999 1133 log_write(input_hist[n].rstrip())
1000 1134 if n in output_hist:
1001 1135 log_write(repr(output_hist[n]),'output')
1002 1136 else:
1003 1137 logger.log_write(input_hist[1:])
1004 1138 if timestamp:
1005 1139 # re-enable timestamping
1006 1140 logger.timestamp = True
1007 1141
1008 1142 print ('Activating auto-logging. '
1009 1143 'Current session state plus future input saved.')
1010 1144 logger.logstate()
1011 1145
1012 1146 def magic_logoff(self,parameter_s=''):
1013 1147 """Temporarily stop logging.
1014 1148
1015 1149 You must have previously started logging."""
1016 1150 self.shell.logger.switch_log(0)
1017 1151
1018 1152 def magic_logon(self,parameter_s=''):
1019 1153 """Restart logging.
1020 1154
1021 1155 This function is for restarting logging which you've temporarily
1022 1156 stopped with %logoff. For starting logging for the first time, you
1023 1157 must use the %logstart function, which allows you to specify an
1024 1158 optional log filename."""
1025 1159
1026 1160 self.shell.logger.switch_log(1)
1027 1161
1028 1162 def magic_logstate(self,parameter_s=''):
1029 1163 """Print the status of the logging system."""
1030 1164
1031 1165 self.shell.logger.logstate()
1032 1166
1033 1167 def magic_pdb(self, parameter_s=''):
1034 1168 """Control the automatic calling of the pdb interactive debugger.
1035 1169
1036 1170 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1037 1171 argument it works as a toggle.
1038 1172
1039 1173 When an exception is triggered, IPython can optionally call the
1040 1174 interactive pdb debugger after the traceback printout. %pdb toggles
1041 1175 this feature on and off.
1042 1176
1043 1177 The initial state of this feature is set in your ipythonrc
1044 1178 configuration file (the variable is called 'pdb').
1045 1179
1046 1180 If you want to just activate the debugger AFTER an exception has fired,
1047 1181 without having to type '%pdb on' and rerunning your code, you can use
1048 1182 the %debug magic."""
1049 1183
1050 1184 par = parameter_s.strip().lower()
1051 1185
1052 1186 if par:
1053 1187 try:
1054 1188 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1055 1189 except KeyError:
1056 1190 print ('Incorrect argument. Use on/1, off/0, '
1057 1191 'or nothing for a toggle.')
1058 1192 return
1059 1193 else:
1060 1194 # toggle
1061 1195 new_pdb = not self.shell.call_pdb
1062 1196
1063 1197 # set on the shell
1064 1198 self.shell.call_pdb = new_pdb
1065 1199 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1066 1200
1067 1201 def magic_debug(self, parameter_s=''):
1068 1202 """Activate the interactive debugger in post-mortem mode.
1069 1203
1070 1204 If an exception has just occurred, this lets you inspect its stack
1071 1205 frames interactively. Note that this will always work only on the last
1072 1206 traceback that occurred, so you must call this quickly after an
1073 1207 exception that you wish to inspect has fired, because if another one
1074 1208 occurs, it clobbers the previous one.
1075 1209
1076 1210 If you want IPython to automatically do this on every exception, see
1077 1211 the %pdb magic for more details.
1078 1212 """
1079 1213
1080 1214 self.shell.debugger(force=True)
1081 1215
1082 1216 def magic_prun(self, parameter_s ='',user_mode=1,
1083 1217 opts=None,arg_lst=None,prog_ns=None):
1084 1218
1085 1219 """Run a statement through the python code profiler.
1086 1220
1087 1221 Usage:\\
1088 1222 %prun [options] statement
1089 1223
1090 1224 The given statement (which doesn't require quote marks) is run via the
1091 1225 python profiler in a manner similar to the profile.run() function.
1092 1226 Namespaces are internally managed to work correctly; profile.run
1093 1227 cannot be used in IPython because it makes certain assumptions about
1094 1228 namespaces which do not hold under IPython.
1095 1229
1096 1230 Options:
1097 1231
1098 1232 -l <limit>: you can place restrictions on what or how much of the
1099 1233 profile gets printed. The limit value can be:
1100 1234
1101 1235 * A string: only information for function names containing this string
1102 1236 is printed.
1103 1237
1104 1238 * An integer: only these many lines are printed.
1105 1239
1106 1240 * A float (between 0 and 1): this fraction of the report is printed
1107 1241 (for example, use a limit of 0.4 to see the topmost 40% only).
1108 1242
1109 1243 You can combine several limits with repeated use of the option. For
1110 1244 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1111 1245 information about class constructors.
1112 1246
1113 1247 -r: return the pstats.Stats object generated by the profiling. This
1114 1248 object has all the information about the profile in it, and you can
1115 1249 later use it for further analysis or in other functions.
1116 1250
1117 1251 -s <key>: sort profile by given key. You can provide more than one key
1118 1252 by using the option several times: '-s key1 -s key2 -s key3...'. The
1119 1253 default sorting key is 'time'.
1120 1254
1121 1255 The following is copied verbatim from the profile documentation
1122 1256 referenced below:
1123 1257
1124 1258 When more than one key is provided, additional keys are used as
1125 1259 secondary criteria when the there is equality in all keys selected
1126 1260 before them.
1127 1261
1128 1262 Abbreviations can be used for any key names, as long as the
1129 1263 abbreviation is unambiguous. The following are the keys currently
1130 1264 defined:
1131 1265
1132 1266 Valid Arg Meaning\\
1133 1267 "calls" call count\\
1134 1268 "cumulative" cumulative time\\
1135 1269 "file" file name\\
1136 1270 "module" file name\\
1137 1271 "pcalls" primitive call count\\
1138 1272 "line" line number\\
1139 1273 "name" function name\\
1140 1274 "nfl" name/file/line\\
1141 1275 "stdname" standard name\\
1142 1276 "time" internal time
1143 1277
1144 1278 Note that all sorts on statistics are in descending order (placing
1145 1279 most time consuming items first), where as name, file, and line number
1146 1280 searches are in ascending order (i.e., alphabetical). The subtle
1147 1281 distinction between "nfl" and "stdname" is that the standard name is a
1148 1282 sort of the name as printed, which means that the embedded line
1149 1283 numbers get compared in an odd way. For example, lines 3, 20, and 40
1150 1284 would (if the file names were the same) appear in the string order
1151 1285 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1152 1286 line numbers. In fact, sort_stats("nfl") is the same as
1153 1287 sort_stats("name", "file", "line").
1154 1288
1155 1289 -T <filename>: save profile results as shown on screen to a text
1156 1290 file. The profile is still shown on screen.
1157 1291
1158 1292 -D <filename>: save (via dump_stats) profile statistics to given
1159 1293 filename. This data is in a format understod by the pstats module, and
1160 1294 is generated by a call to the dump_stats() method of profile
1161 1295 objects. The profile is still shown on screen.
1162 1296
1163 1297 If you want to run complete programs under the profiler's control, use
1164 1298 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1165 1299 contains profiler specific options as described here.
1166 1300
1167 1301 You can read the complete documentation for the profile module with:\\
1168 1302 In [1]: import profile; profile.help() """
1169 1303
1170 1304 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1171 1305 # protect user quote marks
1172 1306 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1173 1307
1174 1308 if user_mode: # regular user call
1175 1309 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1176 1310 list_all=1)
1177 1311 namespace = self.shell.user_ns
1178 1312 else: # called to run a program by %run -p
1179 1313 try:
1180 1314 filename = get_py_filename(arg_lst[0])
1181 1315 except IOError,msg:
1182 1316 error(msg)
1183 1317 return
1184 1318
1185 1319 arg_str = 'execfile(filename,prog_ns)'
1186 1320 namespace = locals()
1187 1321
1188 1322 opts.merge(opts_def)
1189 1323
1190 1324 prof = profile.Profile()
1191 1325 try:
1192 1326 prof = prof.runctx(arg_str,namespace,namespace)
1193 1327 sys_exit = ''
1194 1328 except SystemExit:
1195 1329 sys_exit = """*** SystemExit exception caught in code being profiled."""
1196 1330
1197 1331 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1198 1332
1199 1333 lims = opts.l
1200 1334 if lims:
1201 1335 lims = [] # rebuild lims with ints/floats/strings
1202 1336 for lim in opts.l:
1203 1337 try:
1204 1338 lims.append(int(lim))
1205 1339 except ValueError:
1206 1340 try:
1207 1341 lims.append(float(lim))
1208 1342 except ValueError:
1209 1343 lims.append(lim)
1210 1344
1211 1345 # Trap output.
1212 1346 stdout_trap = StringIO()
1213 1347
1214 1348 if hasattr(stats,'stream'):
1215 1349 # In newer versions of python, the stats object has a 'stream'
1216 1350 # attribute to write into.
1217 1351 stats.stream = stdout_trap
1218 1352 stats.print_stats(*lims)
1219 1353 else:
1220 1354 # For older versions, we manually redirect stdout during printing
1221 1355 sys_stdout = sys.stdout
1222 1356 try:
1223 1357 sys.stdout = stdout_trap
1224 1358 stats.print_stats(*lims)
1225 1359 finally:
1226 1360 sys.stdout = sys_stdout
1227 1361
1228 1362 output = stdout_trap.getvalue()
1229 1363 output = output.rstrip()
1230 1364
1231 1365 page(output,screen_lines=self.shell.rc.screen_length)
1232 1366 print sys_exit,
1233 1367
1234 1368 dump_file = opts.D[0]
1235 1369 text_file = opts.T[0]
1236 1370 if dump_file:
1237 1371 prof.dump_stats(dump_file)
1238 1372 print '\n*** Profile stats marshalled to file',\
1239 1373 `dump_file`+'.',sys_exit
1240 1374 if text_file:
1241 1375 pfile = file(text_file,'w')
1242 1376 pfile.write(output)
1243 1377 pfile.close()
1244 1378 print '\n*** Profile printout saved to text file',\
1245 1379 `text_file`+'.',sys_exit
1246 1380
1247 1381 if opts.has_key('r'):
1248 1382 return stats
1249 1383 else:
1250 1384 return None
1251 1385
1252 1386 def magic_run(self, parameter_s ='',runner=None):
1253 1387 """Run the named file inside IPython as a program.
1254 1388
1255 1389 Usage:\\
1256 1390 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1257 1391
1258 1392 Parameters after the filename are passed as command-line arguments to
1259 1393 the program (put in sys.argv). Then, control returns to IPython's
1260 1394 prompt.
1261 1395
1262 1396 This is similar to running at a system prompt:\\
1263 1397 $ python file args\\
1264 1398 but with the advantage of giving you IPython's tracebacks, and of
1265 1399 loading all variables into your interactive namespace for further use
1266 1400 (unless -p is used, see below).
1267 1401
1268 1402 The file is executed in a namespace initially consisting only of
1269 1403 __name__=='__main__' and sys.argv constructed as indicated. It thus
1270 1404 sees its environment as if it were being run as a stand-alone
1271 1405 program. But after execution, the IPython interactive namespace gets
1272 1406 updated with all variables defined in the program (except for __name__
1273 1407 and sys.argv). This allows for very convenient loading of code for
1274 1408 interactive work, while giving each program a 'clean sheet' to run in.
1275 1409
1276 1410 Options:
1277 1411
1278 1412 -n: __name__ is NOT set to '__main__', but to the running file's name
1279 1413 without extension (as python does under import). This allows running
1280 1414 scripts and reloading the definitions in them without calling code
1281 1415 protected by an ' if __name__ == "__main__" ' clause.
1282 1416
1283 1417 -i: run the file in IPython's namespace instead of an empty one. This
1284 1418 is useful if you are experimenting with code written in a text editor
1285 1419 which depends on variables defined interactively.
1286 1420
1287 1421 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1288 1422 being run. This is particularly useful if IPython is being used to
1289 1423 run unittests, which always exit with a sys.exit() call. In such
1290 1424 cases you are interested in the output of the test results, not in
1291 1425 seeing a traceback of the unittest module.
1292 1426
1293 1427 -t: print timing information at the end of the run. IPython will give
1294 1428 you an estimated CPU time consumption for your script, which under
1295 1429 Unix uses the resource module to avoid the wraparound problems of
1296 1430 time.clock(). Under Unix, an estimate of time spent on system tasks
1297 1431 is also given (for Windows platforms this is reported as 0.0).
1298 1432
1299 1433 If -t is given, an additional -N<N> option can be given, where <N>
1300 1434 must be an integer indicating how many times you want the script to
1301 1435 run. The final timing report will include total and per run results.
1302 1436
1303 1437 For example (testing the script uniq_stable.py):
1304 1438
1305 1439 In [1]: run -t uniq_stable
1306 1440
1307 1441 IPython CPU timings (estimated):\\
1308 1442 User : 0.19597 s.\\
1309 1443 System: 0.0 s.\\
1310 1444
1311 1445 In [2]: run -t -N5 uniq_stable
1312 1446
1313 1447 IPython CPU timings (estimated):\\
1314 1448 Total runs performed: 5\\
1315 1449 Times : Total Per run\\
1316 1450 User : 0.910862 s, 0.1821724 s.\\
1317 1451 System: 0.0 s, 0.0 s.
1318 1452
1319 1453 -d: run your program under the control of pdb, the Python debugger.
1320 1454 This allows you to execute your program step by step, watch variables,
1321 1455 etc. Internally, what IPython does is similar to calling:
1322 1456
1323 1457 pdb.run('execfile("YOURFILENAME")')
1324 1458
1325 1459 with a breakpoint set on line 1 of your file. You can change the line
1326 1460 number for this automatic breakpoint to be <N> by using the -bN option
1327 1461 (where N must be an integer). For example:
1328 1462
1329 1463 %run -d -b40 myscript
1330 1464
1331 1465 will set the first breakpoint at line 40 in myscript.py. Note that
1332 1466 the first breakpoint must be set on a line which actually does
1333 1467 something (not a comment or docstring) for it to stop execution.
1334 1468
1335 1469 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1336 1470 first enter 'c' (without qoutes) to start execution up to the first
1337 1471 breakpoint.
1338 1472
1339 1473 Entering 'help' gives information about the use of the debugger. You
1340 1474 can easily see pdb's full documentation with "import pdb;pdb.help()"
1341 1475 at a prompt.
1342 1476
1343 1477 -p: run program under the control of the Python profiler module (which
1344 1478 prints a detailed report of execution times, function calls, etc).
1345 1479
1346 1480 You can pass other options after -p which affect the behavior of the
1347 1481 profiler itself. See the docs for %prun for details.
1348 1482
1349 1483 In this mode, the program's variables do NOT propagate back to the
1350 1484 IPython interactive namespace (because they remain in the namespace
1351 1485 where the profiler executes them).
1352 1486
1353 1487 Internally this triggers a call to %prun, see its documentation for
1354 1488 details on the options available specifically for profiling.
1355 1489
1356 1490 There is one special usage for which the text above doesn't apply:
1357 1491 if the filename ends with .ipy, the file is run as ipython script,
1358 1492 just as if the commands were written on IPython prompt.
1359 1493 """
1360 1494
1361 1495 # get arguments and set sys.argv for program to be run.
1362 1496 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1363 1497 mode='list',list_all=1)
1364 1498
1365 1499 try:
1366 1500 filename = get_py_filename(arg_lst[0])
1367 1501 except IndexError:
1368 1502 warn('you must provide at least a filename.')
1369 1503 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1370 1504 return
1371 1505 except IOError,msg:
1372 1506 error(msg)
1373 1507 return
1374 1508
1375 1509 if filename.lower().endswith('.ipy'):
1376 1510 self.api.runlines(open(filename).read())
1377 1511 return
1378 1512
1379 1513 # Control the response to exit() calls made by the script being run
1380 1514 exit_ignore = opts.has_key('e')
1381 1515
1382 1516 # Make sure that the running script gets a proper sys.argv as if it
1383 1517 # were run from a system shell.
1384 1518 save_argv = sys.argv # save it for later restoring
1385 1519 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1386 1520
1387 1521 if opts.has_key('i'):
1388 1522 prog_ns = self.shell.user_ns
1389 1523 __name__save = self.shell.user_ns['__name__']
1390 1524 prog_ns['__name__'] = '__main__'
1391 1525 else:
1392 1526 if opts.has_key('n'):
1393 1527 name = os.path.splitext(os.path.basename(filename))[0]
1394 1528 else:
1395 1529 name = '__main__'
1396 1530 prog_ns = {'__name__':name}
1397 1531
1398 1532 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1399 1533 # set the __file__ global in the script's namespace
1400 1534 prog_ns['__file__'] = filename
1401 1535
1402 1536 # pickle fix. See iplib for an explanation. But we need to make sure
1403 1537 # that, if we overwrite __main__, we replace it at the end
1404 1538 if prog_ns['__name__'] == '__main__':
1405 1539 restore_main = sys.modules['__main__']
1406 1540 else:
1407 1541 restore_main = False
1408 1542
1409 1543 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1410 1544
1411 1545 stats = None
1412 1546 try:
1413 1547 if self.shell.has_readline:
1414 1548 self.shell.savehist()
1415 1549
1416 1550 if opts.has_key('p'):
1417 1551 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1418 1552 else:
1419 1553 if opts.has_key('d'):
1420 1554 deb = Debugger.Pdb(self.shell.rc.colors)
1421 1555 # reset Breakpoint state, which is moronically kept
1422 1556 # in a class
1423 1557 bdb.Breakpoint.next = 1
1424 1558 bdb.Breakpoint.bplist = {}
1425 1559 bdb.Breakpoint.bpbynumber = [None]
1426 1560 # Set an initial breakpoint to stop execution
1427 1561 maxtries = 10
1428 1562 bp = int(opts.get('b',[1])[0])
1429 1563 checkline = deb.checkline(filename,bp)
1430 1564 if not checkline:
1431 1565 for bp in range(bp+1,bp+maxtries+1):
1432 1566 if deb.checkline(filename,bp):
1433 1567 break
1434 1568 else:
1435 1569 msg = ("\nI failed to find a valid line to set "
1436 1570 "a breakpoint\n"
1437 1571 "after trying up to line: %s.\n"
1438 1572 "Please set a valid breakpoint manually "
1439 1573 "with the -b option." % bp)
1440 1574 error(msg)
1441 1575 return
1442 1576 # if we find a good linenumber, set the breakpoint
1443 1577 deb.do_break('%s:%s' % (filename,bp))
1444 1578 # Start file run
1445 1579 print "NOTE: Enter 'c' at the",
1446 1580 print "%s prompt to start your script." % deb.prompt
1447 1581 try:
1448 1582 deb.run('execfile("%s")' % filename,prog_ns)
1449 1583
1450 1584 except:
1451 1585 etype, value, tb = sys.exc_info()
1452 1586 # Skip three frames in the traceback: the %run one,
1453 1587 # one inside bdb.py, and the command-line typed by the
1454 1588 # user (run by exec in pdb itself).
1455 1589 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1456 1590 else:
1457 1591 if runner is None:
1458 1592 runner = self.shell.safe_execfile
1459 1593 if opts.has_key('t'):
1460 1594 try:
1461 1595 nruns = int(opts['N'][0])
1462 1596 if nruns < 1:
1463 1597 error('Number of runs must be >=1')
1464 1598 return
1465 1599 except (KeyError):
1466 1600 nruns = 1
1467 1601 if nruns == 1:
1468 1602 t0 = clock2()
1469 1603 runner(filename,prog_ns,prog_ns,
1470 1604 exit_ignore=exit_ignore)
1471 1605 t1 = clock2()
1472 1606 t_usr = t1[0]-t0[0]
1473 1607 t_sys = t1[1]-t1[1]
1474 1608 print "\nIPython CPU timings (estimated):"
1475 1609 print " User : %10s s." % t_usr
1476 1610 print " System: %10s s." % t_sys
1477 1611 else:
1478 1612 runs = range(nruns)
1479 1613 t0 = clock2()
1480 1614 for nr in runs:
1481 1615 runner(filename,prog_ns,prog_ns,
1482 1616 exit_ignore=exit_ignore)
1483 1617 t1 = clock2()
1484 1618 t_usr = t1[0]-t0[0]
1485 1619 t_sys = t1[1]-t1[1]
1486 1620 print "\nIPython CPU timings (estimated):"
1487 1621 print "Total runs performed:",nruns
1488 1622 print " Times : %10s %10s" % ('Total','Per run')
1489 1623 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1490 1624 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1491 1625
1492 1626 else:
1493 1627 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1494 1628 if opts.has_key('i'):
1495 1629 self.shell.user_ns['__name__'] = __name__save
1496 1630 else:
1497 1631 # update IPython interactive namespace
1498 1632 del prog_ns['__name__']
1499 1633 self.shell.user_ns.update(prog_ns)
1500 1634 finally:
1501 1635 sys.argv = save_argv
1502 1636 if restore_main:
1503 1637 sys.modules['__main__'] = restore_main
1504 1638 self.shell.reloadhist()
1505 1639
1506 1640 return stats
1507 1641
1508 1642 def magic_runlog(self, parameter_s =''):
1509 1643 """Run files as logs.
1510 1644
1511 1645 Usage:\\
1512 1646 %runlog file1 file2 ...
1513 1647
1514 1648 Run the named files (treating them as log files) in sequence inside
1515 1649 the interpreter, and return to the prompt. This is much slower than
1516 1650 %run because each line is executed in a try/except block, but it
1517 1651 allows running files with syntax errors in them.
1518 1652
1519 1653 Normally IPython will guess when a file is one of its own logfiles, so
1520 1654 you can typically use %run even for logs. This shorthand allows you to
1521 1655 force any file to be treated as a log file."""
1522 1656
1523 1657 for f in parameter_s.split():
1524 1658 self.shell.safe_execfile(f,self.shell.user_ns,
1525 1659 self.shell.user_ns,islog=1)
1526 1660
1527 1661 def magic_timeit(self, parameter_s =''):
1528 1662 """Time execution of a Python statement or expression
1529 1663
1530 1664 Usage:\\
1531 1665 %timeit [-n<N> -r<R> [-t|-c]] statement
1532 1666
1533 1667 Time execution of a Python statement or expression using the timeit
1534 1668 module.
1535 1669
1536 1670 Options:
1537 1671 -n<N>: execute the given statement <N> times in a loop. If this value
1538 1672 is not given, a fitting value is chosen.
1539 1673
1540 1674 -r<R>: repeat the loop iteration <R> times and take the best result.
1541 1675 Default: 3
1542 1676
1543 1677 -t: use time.time to measure the time, which is the default on Unix.
1544 1678 This function measures wall time.
1545 1679
1546 1680 -c: use time.clock to measure the time, which is the default on
1547 1681 Windows and measures wall time. On Unix, resource.getrusage is used
1548 1682 instead and returns the CPU user time.
1549 1683
1550 1684 -p<P>: use a precision of <P> digits to display the timing result.
1551 1685 Default: 3
1552 1686
1553 1687
1554 1688 Examples:\\
1555 1689 In [1]: %timeit pass
1556 1690 10000000 loops, best of 3: 53.3 ns per loop
1557 1691
1558 1692 In [2]: u = None
1559 1693
1560 1694 In [3]: %timeit u is None
1561 1695 10000000 loops, best of 3: 184 ns per loop
1562 1696
1563 1697 In [4]: %timeit -r 4 u == None
1564 1698 1000000 loops, best of 4: 242 ns per loop
1565 1699
1566 1700 In [5]: import time
1567 1701
1568 1702 In [6]: %timeit -n1 time.sleep(2)
1569 1703 1 loops, best of 3: 2 s per loop
1570 1704
1571 1705
1572 1706 The times reported by %timeit will be slightly higher than those
1573 1707 reported by the timeit.py script when variables are accessed. This is
1574 1708 due to the fact that %timeit executes the statement in the namespace
1575 1709 of the shell, compared with timeit.py, which uses a single setup
1576 1710 statement to import function or create variables. Generally, the bias
1577 1711 does not matter as long as results from timeit.py are not mixed with
1578 1712 those from %timeit."""
1579 1713
1580 1714 import timeit
1581 1715 import math
1582 1716
1583 1717 units = ["s", "ms", "\xc2\xb5s", "ns"]
1584 1718 scaling = [1, 1e3, 1e6, 1e9]
1585 1719
1586 1720 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1587 1721 posix=False)
1588 1722 if stmt == "":
1589 1723 return
1590 1724 timefunc = timeit.default_timer
1591 1725 number = int(getattr(opts, "n", 0))
1592 1726 repeat = int(getattr(opts, "r", timeit.default_repeat))
1593 1727 precision = int(getattr(opts, "p", 3))
1594 1728 if hasattr(opts, "t"):
1595 1729 timefunc = time.time
1596 1730 if hasattr(opts, "c"):
1597 1731 timefunc = clock
1598 1732
1599 1733 timer = timeit.Timer(timer=timefunc)
1600 1734 # this code has tight coupling to the inner workings of timeit.Timer,
1601 1735 # but is there a better way to achieve that the code stmt has access
1602 1736 # to the shell namespace?
1603 1737
1604 1738 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1605 1739 'setup': "pass"}
1606 1740 code = compile(src, "<magic-timeit>", "exec")
1607 1741 ns = {}
1608 1742 exec code in self.shell.user_ns, ns
1609 1743 timer.inner = ns["inner"]
1610 1744
1611 1745 if number == 0:
1612 1746 # determine number so that 0.2 <= total time < 2.0
1613 1747 number = 1
1614 1748 for i in range(1, 10):
1615 1749 number *= 10
1616 1750 if timer.timeit(number) >= 0.2:
1617 1751 break
1618 1752
1619 1753 best = min(timer.repeat(repeat, number)) / number
1620 1754
1621 1755 if best > 0.0:
1622 1756 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1623 1757 else:
1624 1758 order = 3
1625 1759 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1626 1760 precision,
1627 1761 best * scaling[order],
1628 1762 units[order])
1629 1763
1630 1764 def magic_time(self,parameter_s = ''):
1631 1765 """Time execution of a Python statement or expression.
1632 1766
1633 1767 The CPU and wall clock times are printed, and the value of the
1634 1768 expression (if any) is returned. Note that under Win32, system time
1635 1769 is always reported as 0, since it can not be measured.
1636 1770
1637 1771 This function provides very basic timing functionality. In Python
1638 1772 2.3, the timeit module offers more control and sophistication, so this
1639 1773 could be rewritten to use it (patches welcome).
1640 1774
1641 1775 Some examples:
1642 1776
1643 1777 In [1]: time 2**128
1644 1778 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1645 1779 Wall time: 0.00
1646 1780 Out[1]: 340282366920938463463374607431768211456L
1647 1781
1648 1782 In [2]: n = 1000000
1649 1783
1650 1784 In [3]: time sum(range(n))
1651 1785 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1652 1786 Wall time: 1.37
1653 1787 Out[3]: 499999500000L
1654 1788
1655 1789 In [4]: time print 'hello world'
1656 1790 hello world
1657 1791 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1658 1792 Wall time: 0.00
1659 1793 """
1660 1794
1661 1795 # fail immediately if the given expression can't be compiled
1662 1796
1663 1797 expr = self.shell.prefilter(parameter_s,False)
1664 1798
1665 1799 try:
1666 1800 mode = 'eval'
1667 1801 code = compile(expr,'<timed eval>',mode)
1668 1802 except SyntaxError:
1669 1803 mode = 'exec'
1670 1804 code = compile(expr,'<timed exec>',mode)
1671 1805 # skew measurement as little as possible
1672 1806 glob = self.shell.user_ns
1673 1807 clk = clock2
1674 1808 wtime = time.time
1675 1809 # time execution
1676 1810 wall_st = wtime()
1677 1811 if mode=='eval':
1678 1812 st = clk()
1679 1813 out = eval(code,glob)
1680 1814 end = clk()
1681 1815 else:
1682 1816 st = clk()
1683 1817 exec code in glob
1684 1818 end = clk()
1685 1819 out = None
1686 1820 wall_end = wtime()
1687 1821 # Compute actual times and report
1688 1822 wall_time = wall_end-wall_st
1689 1823 cpu_user = end[0]-st[0]
1690 1824 cpu_sys = end[1]-st[1]
1691 1825 cpu_tot = cpu_user+cpu_sys
1692 1826 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1693 1827 (cpu_user,cpu_sys,cpu_tot)
1694 1828 print "Wall time: %.2f" % wall_time
1695 1829 return out
1696 1830
1697 1831 def magic_macro(self,parameter_s = ''):
1698 1832 """Define a set of input lines as a macro for future re-execution.
1699 1833
1700 1834 Usage:\\
1701 1835 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1702 1836
1703 1837 Options:
1704 1838
1705 1839 -r: use 'raw' input. By default, the 'processed' history is used,
1706 1840 so that magics are loaded in their transformed version to valid
1707 1841 Python. If this option is given, the raw input as typed as the
1708 1842 command line is used instead.
1709 1843
1710 1844 This will define a global variable called `name` which is a string
1711 1845 made of joining the slices and lines you specify (n1,n2,... numbers
1712 1846 above) from your input history into a single string. This variable
1713 1847 acts like an automatic function which re-executes those lines as if
1714 1848 you had typed them. You just type 'name' at the prompt and the code
1715 1849 executes.
1716 1850
1717 1851 The notation for indicating number ranges is: n1-n2 means 'use line
1718 1852 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1719 1853 using the lines numbered 5,6 and 7.
1720 1854
1721 1855 Note: as a 'hidden' feature, you can also use traditional python slice
1722 1856 notation, where N:M means numbers N through M-1.
1723 1857
1724 1858 For example, if your history contains (%hist prints it):
1725 1859
1726 1860 44: x=1\\
1727 1861 45: y=3\\
1728 1862 46: z=x+y\\
1729 1863 47: print x\\
1730 1864 48: a=5\\
1731 1865 49: print 'x',x,'y',y\\
1732 1866
1733 1867 you can create a macro with lines 44 through 47 (included) and line 49
1734 1868 called my_macro with:
1735 1869
1736 1870 In [51]: %macro my_macro 44-47 49
1737 1871
1738 1872 Now, typing `my_macro` (without quotes) will re-execute all this code
1739 1873 in one pass.
1740 1874
1741 1875 You don't need to give the line-numbers in order, and any given line
1742 1876 number can appear multiple times. You can assemble macros with any
1743 1877 lines from your input history in any order.
1744 1878
1745 1879 The macro is a simple object which holds its value in an attribute,
1746 1880 but IPython's display system checks for macros and executes them as
1747 1881 code instead of printing them when you type their name.
1748 1882
1749 1883 You can view a macro's contents by explicitly printing it with:
1750 1884
1751 1885 'print macro_name'.
1752 1886
1753 1887 For one-off cases which DON'T contain magic function calls in them you
1754 1888 can obtain similar results by explicitly executing slices from your
1755 1889 input history with:
1756 1890
1757 1891 In [60]: exec In[44:48]+In[49]"""
1758 1892
1759 1893 opts,args = self.parse_options(parameter_s,'r',mode='list')
1760 1894 if not args:
1761 1895 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1762 1896 macs.sort()
1763 1897 return macs
1764 1898 name,ranges = args[0], args[1:]
1765 1899 #print 'rng',ranges # dbg
1766 1900 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1767 1901 macro = Macro(lines)
1768 1902 self.shell.user_ns.update({name:macro})
1769 1903 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1770 1904 print 'Macro contents:'
1771 1905 print macro,
1772 1906
1773 1907 def magic_save(self,parameter_s = ''):
1774 1908 """Save a set of lines to a given filename.
1775 1909
1776 1910 Usage:\\
1777 1911 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1778 1912
1779 1913 Options:
1780 1914
1781 1915 -r: use 'raw' input. By default, the 'processed' history is used,
1782 1916 so that magics are loaded in their transformed version to valid
1783 1917 Python. If this option is given, the raw input as typed as the
1784 1918 command line is used instead.
1785 1919
1786 1920 This function uses the same syntax as %macro for line extraction, but
1787 1921 instead of creating a macro it saves the resulting string to the
1788 1922 filename you specify.
1789 1923
1790 1924 It adds a '.py' extension to the file if you don't do so yourself, and
1791 1925 it asks for confirmation before overwriting existing files."""
1792 1926
1793 1927 opts,args = self.parse_options(parameter_s,'r',mode='list')
1794 1928 fname,ranges = args[0], args[1:]
1795 1929 if not fname.endswith('.py'):
1796 1930 fname += '.py'
1797 1931 if os.path.isfile(fname):
1798 1932 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1799 1933 if ans.lower() not in ['y','yes']:
1800 1934 print 'Operation cancelled.'
1801 1935 return
1802 1936 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1803 1937 f = file(fname,'w')
1804 1938 f.write(cmds)
1805 1939 f.close()
1806 1940 print 'The following commands were written to file `%s`:' % fname
1807 1941 print cmds
1808 1942
1809 1943 def _edit_macro(self,mname,macro):
1810 1944 """open an editor with the macro data in a file"""
1811 1945 filename = self.shell.mktempfile(macro.value)
1812 1946 self.shell.hooks.editor(filename)
1813 1947
1814 1948 # and make a new macro object, to replace the old one
1815 1949 mfile = open(filename)
1816 1950 mvalue = mfile.read()
1817 1951 mfile.close()
1818 1952 self.shell.user_ns[mname] = Macro(mvalue)
1819 1953
1820 1954 def magic_ed(self,parameter_s=''):
1821 1955 """Alias to %edit."""
1822 1956 return self.magic_edit(parameter_s)
1823 1957
1824 1958 def magic_edit(self,parameter_s='',last_call=['','']):
1825 1959 """Bring up an editor and execute the resulting code.
1826 1960
1827 1961 Usage:
1828 1962 %edit [options] [args]
1829 1963
1830 1964 %edit runs IPython's editor hook. The default version of this hook is
1831 1965 set to call the __IPYTHON__.rc.editor command. This is read from your
1832 1966 environment variable $EDITOR. If this isn't found, it will default to
1833 1967 vi under Linux/Unix and to notepad under Windows. See the end of this
1834 1968 docstring for how to change the editor hook.
1835 1969
1836 1970 You can also set the value of this editor via the command line option
1837 1971 '-editor' or in your ipythonrc file. This is useful if you wish to use
1838 1972 specifically for IPython an editor different from your typical default
1839 1973 (and for Windows users who typically don't set environment variables).
1840 1974
1841 1975 This command allows you to conveniently edit multi-line code right in
1842 1976 your IPython session.
1843 1977
1844 1978 If called without arguments, %edit opens up an empty editor with a
1845 1979 temporary file and will execute the contents of this file when you
1846 1980 close it (don't forget to save it!).
1847 1981
1848 1982
1849 1983 Options:
1850 1984
1851 1985 -n <number>: open the editor at a specified line number. By default,
1852 1986 the IPython editor hook uses the unix syntax 'editor +N filename', but
1853 1987 you can configure this by providing your own modified hook if your
1854 1988 favorite editor supports line-number specifications with a different
1855 1989 syntax.
1856 1990
1857 1991 -p: this will call the editor with the same data as the previous time
1858 1992 it was used, regardless of how long ago (in your current session) it
1859 1993 was.
1860 1994
1861 1995 -r: use 'raw' input. This option only applies to input taken from the
1862 1996 user's history. By default, the 'processed' history is used, so that
1863 1997 magics are loaded in their transformed version to valid Python. If
1864 1998 this option is given, the raw input as typed as the command line is
1865 1999 used instead. When you exit the editor, it will be executed by
1866 2000 IPython's own processor.
1867 2001
1868 2002 -x: do not execute the edited code immediately upon exit. This is
1869 2003 mainly useful if you are editing programs which need to be called with
1870 2004 command line arguments, which you can then do using %run.
1871 2005
1872 2006
1873 2007 Arguments:
1874 2008
1875 2009 If arguments are given, the following possibilites exist:
1876 2010
1877 2011 - The arguments are numbers or pairs of colon-separated numbers (like
1878 2012 1 4:8 9). These are interpreted as lines of previous input to be
1879 2013 loaded into the editor. The syntax is the same of the %macro command.
1880 2014
1881 2015 - If the argument doesn't start with a number, it is evaluated as a
1882 2016 variable and its contents loaded into the editor. You can thus edit
1883 2017 any string which contains python code (including the result of
1884 2018 previous edits).
1885 2019
1886 2020 - If the argument is the name of an object (other than a string),
1887 2021 IPython will try to locate the file where it was defined and open the
1888 2022 editor at the point where it is defined. You can use `%edit function`
1889 2023 to load an editor exactly at the point where 'function' is defined,
1890 2024 edit it and have the file be executed automatically.
1891 2025
1892 2026 If the object is a macro (see %macro for details), this opens up your
1893 2027 specified editor with a temporary file containing the macro's data.
1894 2028 Upon exit, the macro is reloaded with the contents of the file.
1895 2029
1896 2030 Note: opening at an exact line is only supported under Unix, and some
1897 2031 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1898 2032 '+NUMBER' parameter necessary for this feature. Good editors like
1899 2033 (X)Emacs, vi, jed, pico and joe all do.
1900 2034
1901 2035 - If the argument is not found as a variable, IPython will look for a
1902 2036 file with that name (adding .py if necessary) and load it into the
1903 2037 editor. It will execute its contents with execfile() when you exit,
1904 2038 loading any code in the file into your interactive namespace.
1905 2039
1906 2040 After executing your code, %edit will return as output the code you
1907 2041 typed in the editor (except when it was an existing file). This way
1908 2042 you can reload the code in further invocations of %edit as a variable,
1909 2043 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1910 2044 the output.
1911 2045
1912 2046 Note that %edit is also available through the alias %ed.
1913 2047
1914 2048 This is an example of creating a simple function inside the editor and
1915 2049 then modifying it. First, start up the editor:
1916 2050
1917 2051 In [1]: ed\\
1918 2052 Editing... done. Executing edited code...\\
1919 2053 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1920 2054
1921 2055 We can then call the function foo():
1922 2056
1923 2057 In [2]: foo()\\
1924 2058 foo() was defined in an editing session
1925 2059
1926 2060 Now we edit foo. IPython automatically loads the editor with the
1927 2061 (temporary) file where foo() was previously defined:
1928 2062
1929 2063 In [3]: ed foo\\
1930 2064 Editing... done. Executing edited code...
1931 2065
1932 2066 And if we call foo() again we get the modified version:
1933 2067
1934 2068 In [4]: foo()\\
1935 2069 foo() has now been changed!
1936 2070
1937 2071 Here is an example of how to edit a code snippet successive
1938 2072 times. First we call the editor:
1939 2073
1940 2074 In [8]: ed\\
1941 2075 Editing... done. Executing edited code...\\
1942 2076 hello\\
1943 2077 Out[8]: "print 'hello'\\n"
1944 2078
1945 2079 Now we call it again with the previous output (stored in _):
1946 2080
1947 2081 In [9]: ed _\\
1948 2082 Editing... done. Executing edited code...\\
1949 2083 hello world\\
1950 2084 Out[9]: "print 'hello world'\\n"
1951 2085
1952 2086 Now we call it with the output #8 (stored in _8, also as Out[8]):
1953 2087
1954 2088 In [10]: ed _8\\
1955 2089 Editing... done. Executing edited code...\\
1956 2090 hello again\\
1957 2091 Out[10]: "print 'hello again'\\n"
1958 2092
1959 2093
1960 2094 Changing the default editor hook:
1961 2095
1962 2096 If you wish to write your own editor hook, you can put it in a
1963 2097 configuration file which you load at startup time. The default hook
1964 2098 is defined in the IPython.hooks module, and you can use that as a
1965 2099 starting example for further modifications. That file also has
1966 2100 general instructions on how to set a new hook for use once you've
1967 2101 defined it."""
1968 2102
1969 2103 # FIXME: This function has become a convoluted mess. It needs a
1970 2104 # ground-up rewrite with clean, simple logic.
1971 2105
1972 2106 def make_filename(arg):
1973 2107 "Make a filename from the given args"
1974 2108 try:
1975 2109 filename = get_py_filename(arg)
1976 2110 except IOError:
1977 2111 if args.endswith('.py'):
1978 2112 filename = arg
1979 2113 else:
1980 2114 filename = None
1981 2115 return filename
1982 2116
1983 2117 # custom exceptions
1984 2118 class DataIsObject(Exception): pass
1985 2119
1986 2120 opts,args = self.parse_options(parameter_s,'prxn:')
1987 2121 # Set a few locals from the options for convenience:
1988 2122 opts_p = opts.has_key('p')
1989 2123 opts_r = opts.has_key('r')
1990 2124
1991 2125 # Default line number value
1992 2126 lineno = opts.get('n',None)
1993 2127
1994 2128 if opts_p:
1995 2129 args = '_%s' % last_call[0]
1996 2130 if not self.shell.user_ns.has_key(args):
1997 2131 args = last_call[1]
1998 2132
1999 2133 # use last_call to remember the state of the previous call, but don't
2000 2134 # let it be clobbered by successive '-p' calls.
2001 2135 try:
2002 2136 last_call[0] = self.shell.outputcache.prompt_count
2003 2137 if not opts_p:
2004 2138 last_call[1] = parameter_s
2005 2139 except:
2006 2140 pass
2007 2141
2008 2142 # by default this is done with temp files, except when the given
2009 2143 # arg is a filename
2010 2144 use_temp = 1
2011 2145
2012 2146 if re.match(r'\d',args):
2013 2147 # Mode where user specifies ranges of lines, like in %macro.
2014 2148 # This means that you can't edit files whose names begin with
2015 2149 # numbers this way. Tough.
2016 2150 ranges = args.split()
2017 2151 data = ''.join(self.extract_input_slices(ranges,opts_r))
2018 2152 elif args.endswith('.py'):
2019 2153 filename = make_filename(args)
2020 2154 data = ''
2021 2155 use_temp = 0
2022 2156 elif args:
2023 2157 try:
2024 2158 # Load the parameter given as a variable. If not a string,
2025 2159 # process it as an object instead (below)
2026 2160
2027 2161 #print '*** args',args,'type',type(args) # dbg
2028 2162 data = eval(args,self.shell.user_ns)
2029 2163 if not type(data) in StringTypes:
2030 2164 raise DataIsObject
2031 2165
2032 2166 except (NameError,SyntaxError):
2033 2167 # given argument is not a variable, try as a filename
2034 2168 filename = make_filename(args)
2035 2169 if filename is None:
2036 2170 warn("Argument given (%s) can't be found as a variable "
2037 2171 "or as a filename." % args)
2038 2172 return
2039 2173
2040 2174 data = ''
2041 2175 use_temp = 0
2042 2176 except DataIsObject:
2043 2177
2044 2178 # macros have a special edit function
2045 2179 if isinstance(data,Macro):
2046 2180 self._edit_macro(args,data)
2047 2181 return
2048 2182
2049 2183 # For objects, try to edit the file where they are defined
2050 2184 try:
2051 2185 filename = inspect.getabsfile(data)
2052 2186 datafile = 1
2053 2187 except TypeError:
2054 2188 filename = make_filename(args)
2055 2189 datafile = 1
2056 2190 warn('Could not find file where `%s` is defined.\n'
2057 2191 'Opening a file named `%s`' % (args,filename))
2058 2192 # Now, make sure we can actually read the source (if it was in
2059 2193 # a temp file it's gone by now).
2060 2194 if datafile:
2061 2195 try:
2062 2196 if lineno is None:
2063 2197 lineno = inspect.getsourcelines(data)[1]
2064 2198 except IOError:
2065 2199 filename = make_filename(args)
2066 2200 if filename is None:
2067 2201 warn('The file `%s` where `%s` was defined cannot '
2068 2202 'be read.' % (filename,data))
2069 2203 return
2070 2204 use_temp = 0
2071 2205 else:
2072 2206 data = ''
2073 2207
2074 2208 if use_temp:
2075 2209 filename = self.shell.mktempfile(data)
2076 2210 print 'IPython will make a temporary file named:',filename
2077 2211
2078 2212 # do actual editing here
2079 2213 print 'Editing...',
2080 2214 sys.stdout.flush()
2081 2215 self.shell.hooks.editor(filename,lineno)
2082 2216 if opts.has_key('x'): # -x prevents actual execution
2083 2217 print
2084 2218 else:
2085 2219 print 'done. Executing edited code...'
2086 2220 if opts_r:
2087 2221 self.shell.runlines(file_read(filename))
2088 2222 else:
2089 2223 self.shell.safe_execfile(filename,self.shell.user_ns,
2090 2224 self.shell.user_ns)
2091 2225 if use_temp:
2092 2226 try:
2093 2227 return open(filename).read()
2094 2228 except IOError,msg:
2095 2229 if msg.filename == filename:
2096 2230 warn('File not found. Did you forget to save?')
2097 2231 return
2098 2232 else:
2099 2233 self.shell.showtraceback()
2100 2234
2101 2235 def magic_xmode(self,parameter_s = ''):
2102 2236 """Switch modes for the exception handlers.
2103 2237
2104 2238 Valid modes: Plain, Context and Verbose.
2105 2239
2106 2240 If called without arguments, acts as a toggle."""
2107 2241
2108 2242 def xmode_switch_err(name):
2109 2243 warn('Error changing %s exception modes.\n%s' %
2110 2244 (name,sys.exc_info()[1]))
2111 2245
2112 2246 shell = self.shell
2113 2247 new_mode = parameter_s.strip().capitalize()
2114 2248 try:
2115 2249 shell.InteractiveTB.set_mode(mode=new_mode)
2116 2250 print 'Exception reporting mode:',shell.InteractiveTB.mode
2117 2251 except:
2118 2252 xmode_switch_err('user')
2119 2253
2120 2254 # threaded shells use a special handler in sys.excepthook
2121 2255 if shell.isthreaded:
2122 2256 try:
2123 2257 shell.sys_excepthook.set_mode(mode=new_mode)
2124 2258 except:
2125 2259 xmode_switch_err('threaded')
2126 2260
2127 2261 def magic_colors(self,parameter_s = ''):
2128 2262 """Switch color scheme for prompts, info system and exception handlers.
2129 2263
2130 2264 Currently implemented schemes: NoColor, Linux, LightBG.
2131 2265
2132 2266 Color scheme names are not case-sensitive."""
2133 2267
2134 2268 def color_switch_err(name):
2135 2269 warn('Error changing %s color schemes.\n%s' %
2136 2270 (name,sys.exc_info()[1]))
2137 2271
2138 2272
2139 2273 new_scheme = parameter_s.strip()
2140 2274 if not new_scheme:
2141 2275 print 'You must specify a color scheme.'
2142 2276 return
2143 2277 # local shortcut
2144 2278 shell = self.shell
2145 2279
2146 2280 import IPython.rlineimpl as readline
2147 2281
2148 2282 if not readline.have_readline and sys.platform == "win32":
2149 2283 msg = """\
2150 2284 Proper color support under MS Windows requires the pyreadline library.
2151 2285 You can find it at:
2152 2286 http://ipython.scipy.org/moin/PyReadline/Intro
2153 2287 Gary's readline needs the ctypes module, from:
2154 2288 http://starship.python.net/crew/theller/ctypes
2155 2289 (Note that ctypes is already part of Python versions 2.5 and newer).
2156 2290
2157 2291 Defaulting color scheme to 'NoColor'"""
2158 2292 new_scheme = 'NoColor'
2159 2293 warn(msg)
2160 2294
2161 2295 # readline option is 0
2162 2296 if not shell.has_readline:
2163 2297 new_scheme = 'NoColor'
2164 2298
2165 2299 # Set prompt colors
2166 2300 try:
2167 2301 shell.outputcache.set_colors(new_scheme)
2168 2302 except:
2169 2303 color_switch_err('prompt')
2170 2304 else:
2171 2305 shell.rc.colors = \
2172 2306 shell.outputcache.color_table.active_scheme_name
2173 2307 # Set exception colors
2174 2308 try:
2175 2309 shell.InteractiveTB.set_colors(scheme = new_scheme)
2176 2310 shell.SyntaxTB.set_colors(scheme = new_scheme)
2177 2311 except:
2178 2312 color_switch_err('exception')
2179 2313
2180 2314 # threaded shells use a verbose traceback in sys.excepthook
2181 2315 if shell.isthreaded:
2182 2316 try:
2183 2317 shell.sys_excepthook.set_colors(scheme=new_scheme)
2184 2318 except:
2185 2319 color_switch_err('system exception handler')
2186 2320
2187 2321 # Set info (for 'object?') colors
2188 2322 if shell.rc.color_info:
2189 2323 try:
2190 2324 shell.inspector.set_active_scheme(new_scheme)
2191 2325 except:
2192 2326 color_switch_err('object inspector')
2193 2327 else:
2194 2328 shell.inspector.set_active_scheme('NoColor')
2195 2329
2196 2330 def magic_color_info(self,parameter_s = ''):
2197 2331 """Toggle color_info.
2198 2332
2199 2333 The color_info configuration parameter controls whether colors are
2200 2334 used for displaying object details (by things like %psource, %pfile or
2201 2335 the '?' system). This function toggles this value with each call.
2202 2336
2203 2337 Note that unless you have a fairly recent pager (less works better
2204 2338 than more) in your system, using colored object information displays
2205 2339 will not work properly. Test it and see."""
2206 2340
2207 2341 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2208 2342 self.magic_colors(self.shell.rc.colors)
2209 2343 print 'Object introspection functions have now coloring:',
2210 2344 print ['OFF','ON'][self.shell.rc.color_info]
2211 2345
2212 2346 def magic_Pprint(self, parameter_s=''):
2213 2347 """Toggle pretty printing on/off."""
2214 2348
2215 2349 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2216 2350 print 'Pretty printing has been turned', \
2217 2351 ['OFF','ON'][self.shell.rc.pprint]
2218 2352
2219 2353 def magic_exit(self, parameter_s=''):
2220 2354 """Exit IPython, confirming if configured to do so.
2221 2355
2222 2356 You can configure whether IPython asks for confirmation upon exit by
2223 2357 setting the confirm_exit flag in the ipythonrc file."""
2224 2358
2225 2359 self.shell.exit()
2226 2360
2227 2361 def magic_quit(self, parameter_s=''):
2228 2362 """Exit IPython, confirming if configured to do so (like %exit)"""
2229 2363
2230 2364 self.shell.exit()
2231 2365
2232 2366 def magic_Exit(self, parameter_s=''):
2233 2367 """Exit IPython without confirmation."""
2234 2368
2235 2369 self.shell.exit_now = True
2236 2370
2237 2371 #......................................................................
2238 2372 # Functions to implement unix shell-type things
2239 2373
2240 2374 def magic_alias(self, parameter_s = ''):
2241 2375 """Define an alias for a system command.
2242 2376
2243 2377 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2244 2378
2245 2379 Then, typing 'alias_name params' will execute the system command 'cmd
2246 2380 params' (from your underlying operating system).
2247 2381
2248 2382 Aliases have lower precedence than magic functions and Python normal
2249 2383 variables, so if 'foo' is both a Python variable and an alias, the
2250 2384 alias can not be executed until 'del foo' removes the Python variable.
2251 2385
2252 2386 You can use the %l specifier in an alias definition to represent the
2253 2387 whole line when the alias is called. For example:
2254 2388
2255 2389 In [2]: alias all echo "Input in brackets: <%l>"\\
2256 2390 In [3]: all hello world\\
2257 2391 Input in brackets: <hello world>
2258 2392
2259 2393 You can also define aliases with parameters using %s specifiers (one
2260 2394 per parameter):
2261 2395
2262 2396 In [1]: alias parts echo first %s second %s\\
2263 2397 In [2]: %parts A B\\
2264 2398 first A second B\\
2265 2399 In [3]: %parts A\\
2266 2400 Incorrect number of arguments: 2 expected.\\
2267 2401 parts is an alias to: 'echo first %s second %s'
2268 2402
2269 2403 Note that %l and %s are mutually exclusive. You can only use one or
2270 2404 the other in your aliases.
2271 2405
2272 2406 Aliases expand Python variables just like system calls using ! or !!
2273 2407 do: all expressions prefixed with '$' get expanded. For details of
2274 2408 the semantic rules, see PEP-215:
2275 2409 http://www.python.org/peps/pep-0215.html. This is the library used by
2276 2410 IPython for variable expansion. If you want to access a true shell
2277 2411 variable, an extra $ is necessary to prevent its expansion by IPython:
2278 2412
2279 2413 In [6]: alias show echo\\
2280 2414 In [7]: PATH='A Python string'\\
2281 2415 In [8]: show $PATH\\
2282 2416 A Python string\\
2283 2417 In [9]: show $$PATH\\
2284 2418 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2285 2419
2286 2420 You can use the alias facility to acess all of $PATH. See the %rehash
2287 2421 and %rehashx functions, which automatically create aliases for the
2288 2422 contents of your $PATH.
2289 2423
2290 2424 If called with no parameters, %alias prints the current alias table."""
2291 2425
2292 2426 par = parameter_s.strip()
2293 2427 if not par:
2294 2428 stored = self.db.get('stored_aliases', {} )
2295 2429 atab = self.shell.alias_table
2296 2430 aliases = atab.keys()
2297 2431 aliases.sort()
2298 2432 res = []
2299 2433 showlast = []
2300 2434 for alias in aliases:
2301 2435 special = False
2302 2436 try:
2303 2437 tgt = atab[alias][1]
2304 2438 except (TypeError, AttributeError):
2305 2439 # unsubscriptable? probably a callable
2306 2440 tgt = atab[alias]
2307 2441 special = True
2308 2442 # 'interesting' aliases
2309 2443 if (alias in stored or
2310 2444 special or
2311 2445 alias.lower() != os.path.splitext(tgt)[0].lower() or
2312 2446 ' ' in tgt):
2313 2447 showlast.append((alias, tgt))
2314 2448 else:
2315 2449 res.append((alias, tgt ))
2316 2450
2317 2451 # show most interesting aliases last
2318 2452 res.extend(showlast)
2319 2453 print "Total number of aliases:",len(aliases)
2320 2454 return res
2321 2455 try:
2322 2456 alias,cmd = par.split(None,1)
2323 2457 except:
2324 2458 print OInspect.getdoc(self.magic_alias)
2325 2459 else:
2326 2460 nargs = cmd.count('%s')
2327 2461 if nargs>0 and cmd.find('%l')>=0:
2328 2462 error('The %s and %l specifiers are mutually exclusive '
2329 2463 'in alias definitions.')
2330 2464 else: # all looks OK
2331 2465 self.shell.alias_table[alias] = (nargs,cmd)
2332 2466 self.shell.alias_table_validate(verbose=0)
2333 2467 # end magic_alias
2334 2468
2335 2469 def magic_unalias(self, parameter_s = ''):
2336 2470 """Remove an alias"""
2337 2471
2338 2472 aname = parameter_s.strip()
2339 2473 if aname in self.shell.alias_table:
2340 2474 del self.shell.alias_table[aname]
2341 2475 stored = self.db.get('stored_aliases', {} )
2342 2476 if aname in stored:
2343 2477 print "Removing %stored alias",aname
2344 2478 del stored[aname]
2345 2479 self.db['stored_aliases'] = stored
2346 2480
2347 2481
2348 2482 def magic_rehashx(self, parameter_s = ''):
2349 2483 """Update the alias table with all executable files in $PATH.
2350 2484
2351 2485 This version explicitly checks that every entry in $PATH is a file
2352 2486 with execute access (os.X_OK), so it is much slower than %rehash.
2353 2487
2354 2488 Under Windows, it checks executability as a match agains a
2355 2489 '|'-separated string of extensions, stored in the IPython config
2356 2490 variable win_exec_ext. This defaults to 'exe|com|bat'.
2357 2491
2358 2492 This function also resets the root module cache of module completer,
2359 2493 used on slow filesystems.
2360 2494 """
2361 2495
2362 2496
2363 2497 ip = self.api
2364 2498
2365 2499 # for the benefit of module completer in ipy_completers.py
2366 2500 del ip.db['rootmodules']
2367 2501
2368 2502 path = [os.path.abspath(os.path.expanduser(p)) for p in
2369 2503 os.environ.get('PATH','').split(os.pathsep)]
2370 2504 path = filter(os.path.isdir,path)
2371 2505
2372 2506 alias_table = self.shell.alias_table
2373 2507 syscmdlist = []
2374 2508 if os.name == 'posix':
2375 2509 isexec = lambda fname:os.path.isfile(fname) and \
2376 2510 os.access(fname,os.X_OK)
2377 2511 else:
2378 2512
2379 2513 try:
2380 2514 winext = os.environ['pathext'].replace(';','|').replace('.','')
2381 2515 except KeyError:
2382 2516 winext = 'exe|com|bat|py'
2383 2517 if 'py' not in winext:
2384 2518 winext += '|py'
2385 2519 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2386 2520 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2387 2521 savedir = os.getcwd()
2388 2522 try:
2389 2523 # write the whole loop for posix/Windows so we don't have an if in
2390 2524 # the innermost part
2391 2525 if os.name == 'posix':
2392 2526 for pdir in path:
2393 2527 os.chdir(pdir)
2394 2528 for ff in os.listdir(pdir):
2395 2529 if isexec(ff) and ff not in self.shell.no_alias:
2396 2530 # each entry in the alias table must be (N,name),
2397 2531 # where N is the number of positional arguments of the
2398 2532 # alias.
2399 2533 alias_table[ff] = (0,ff)
2400 2534 syscmdlist.append(ff)
2401 2535 else:
2402 2536 for pdir in path:
2403 2537 os.chdir(pdir)
2404 2538 for ff in os.listdir(pdir):
2405 2539 base, ext = os.path.splitext(ff)
2406 2540 if isexec(ff) and base not in self.shell.no_alias:
2407 2541 if ext.lower() == '.exe':
2408 2542 ff = base
2409 2543 alias_table[base.lower()] = (0,ff)
2410 2544 syscmdlist.append(ff)
2411 2545 # Make sure the alias table doesn't contain keywords or builtins
2412 2546 self.shell.alias_table_validate()
2413 2547 # Call again init_auto_alias() so we get 'rm -i' and other
2414 2548 # modified aliases since %rehashx will probably clobber them
2415 2549
2416 2550 # no, we don't want them. if %rehashx clobbers them, good,
2417 2551 # we'll probably get better versions
2418 2552 # self.shell.init_auto_alias()
2419 2553 db = ip.db
2420 2554 db['syscmdlist'] = syscmdlist
2421 2555 finally:
2422 2556 os.chdir(savedir)
2423 2557
2424 2558 def magic_pwd(self, parameter_s = ''):
2425 2559 """Return the current working directory path."""
2426 2560 return os.getcwd()
2427 2561
2428 2562 def magic_cd(self, parameter_s=''):
2429 2563 """Change the current working directory.
2430 2564
2431 2565 This command automatically maintains an internal list of directories
2432 2566 you visit during your IPython session, in the variable _dh. The
2433 2567 command %dhist shows this history nicely formatted. You can also
2434 2568 do 'cd -<tab>' to see directory history conveniently.
2435 2569
2436 2570 Usage:
2437 2571
2438 2572 cd 'dir': changes to directory 'dir'.
2439 2573
2440 2574 cd -: changes to the last visited directory.
2441 2575
2442 2576 cd -<n>: changes to the n-th directory in the directory history.
2443 2577
2444 2578 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2445 2579 (note: cd <bookmark_name> is enough if there is no
2446 2580 directory <bookmark_name>, but a bookmark with the name exists.)
2447 2581 'cd -b <tab>' allows you to tab-complete bookmark names.
2448 2582
2449 2583 Options:
2450 2584
2451 2585 -q: quiet. Do not print the working directory after the cd command is
2452 2586 executed. By default IPython's cd command does print this directory,
2453 2587 since the default prompts do not display path information.
2454 2588
2455 2589 Note that !cd doesn't work for this purpose because the shell where
2456 2590 !command runs is immediately discarded after executing 'command'."""
2457 2591
2458 2592 parameter_s = parameter_s.strip()
2459 2593 #bkms = self.shell.persist.get("bookmarks",{})
2460 2594
2461 2595 numcd = re.match(r'(-)(\d+)$',parameter_s)
2462 2596 # jump in directory history by number
2463 2597 if numcd:
2464 2598 nn = int(numcd.group(2))
2465 2599 try:
2466 2600 ps = self.shell.user_ns['_dh'][nn]
2467 2601 except IndexError:
2468 2602 print 'The requested directory does not exist in history.'
2469 2603 return
2470 2604 else:
2471 2605 opts = {}
2472 2606 else:
2473 2607 #turn all non-space-escaping backslashes to slashes,
2474 2608 # for c:\windows\directory\names\
2475 2609 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2476 2610 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2477 2611 # jump to previous
2478 2612 if ps == '-':
2479 2613 try:
2480 2614 ps = self.shell.user_ns['_dh'][-2]
2481 2615 except IndexError:
2482 2616 print 'No previous directory to change to.'
2483 2617 return
2484 2618 # jump to bookmark if needed
2485 2619 else:
2486 2620 if not os.path.isdir(ps) or opts.has_key('b'):
2487 2621 bkms = self.db.get('bookmarks', {})
2488 2622
2489 2623 if bkms.has_key(ps):
2490 2624 target = bkms[ps]
2491 2625 print '(bookmark:%s) -> %s' % (ps,target)
2492 2626 ps = target
2493 2627 else:
2494 2628 if opts.has_key('b'):
2495 2629 error("Bookmark '%s' not found. "
2496 2630 "Use '%%bookmark -l' to see your bookmarks." % ps)
2497 2631 return
2498 2632
2499 2633 # at this point ps should point to the target dir
2500 2634 if ps:
2501 2635 try:
2502 2636 os.chdir(os.path.expanduser(ps))
2503 2637 if self.shell.rc.term_title:
2504 2638 #print 'set term title:',self.shell.rc.term_title # dbg
2505 2639 ttitle = 'IPy ' + abbrev_cwd()
2506 2640 platutils.set_term_title(ttitle)
2507 2641 except OSError:
2508 2642 print sys.exc_info()[1]
2509 2643 else:
2510 2644 cwd = os.getcwd()
2511 2645 dhist = self.shell.user_ns['_dh']
2512 2646 dhist.append(cwd)
2513 2647 self.db['dhist'] = compress_dhist(dhist)[-100:]
2514 2648
2515 2649 else:
2516 2650 os.chdir(self.shell.home_dir)
2517 2651 if self.shell.rc.term_title:
2518 2652 platutils.set_term_title("IPy ~")
2519 2653 cwd = os.getcwd()
2520 2654 dhist = self.shell.user_ns['_dh']
2521 2655 dhist.append(cwd)
2522 2656 self.db['dhist'] = compress_dhist(dhist)[-100:]
2523 2657 if not 'q' in opts and self.shell.user_ns['_dh']:
2524 2658 print self.shell.user_ns['_dh'][-1]
2525 2659
2526 2660
2527 2661 def magic_env(self, parameter_s=''):
2528 2662 """List environment variables."""
2529 2663
2530 2664 return os.environ.data
2531 2665
2532 2666 def magic_pushd(self, parameter_s=''):
2533 2667 """Place the current dir on stack and change directory.
2534 2668
2535 2669 Usage:\\
2536 2670 %pushd ['dirname']
2537 2671
2538 2672 %pushd with no arguments does a %pushd to your home directory.
2539 2673 """
2540 2674 if parameter_s == '': parameter_s = '~'
2541 2675 dir_s = self.shell.dir_stack
2542 2676 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2543 2677 os.path.expanduser(self.shell.dir_stack[0]):
2544 2678 try:
2545 2679 self.magic_cd(parameter_s)
2546 2680 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2547 2681 self.magic_dirs()
2548 2682 except:
2549 2683 print 'Invalid directory'
2550 2684 else:
2551 2685 print 'You are already there!'
2552 2686
2553 2687 def magic_popd(self, parameter_s=''):
2554 2688 """Change to directory popped off the top of the stack.
2555 2689 """
2556 2690 if len (self.shell.dir_stack) > 1:
2557 2691 self.shell.dir_stack.pop(0)
2558 2692 self.magic_cd(self.shell.dir_stack[0])
2559 2693 print self.shell.dir_stack[0]
2560 2694 else:
2561 2695 print "You can't remove the starting directory from the stack:",\
2562 2696 self.shell.dir_stack
2563 2697
2564 2698 def magic_dirs(self, parameter_s=''):
2565 2699 """Return the current directory stack."""
2566 2700
2567 2701 return self.shell.dir_stack[:]
2568 2702
2703 def magic_dhist(self, parameter_s=''):
2704 """Print your history of visited directories.
2705
2706 %dhist -> print full history\\
2707 %dhist n -> print last n entries only\\
2708 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2709
2710 This history is automatically maintained by the %cd command, and
2711 always available as the global list variable _dh. You can use %cd -<n>
2712 to go to directory number <n>."""
2713
2714 dh = self.shell.user_ns['_dh']
2715 if parameter_s:
2716 try:
2717 args = map(int,parameter_s.split())
2718 except:
2719 self.arg_err(Magic.magic_dhist)
2720 return
2721 if len(args) == 1:
2722 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2723 elif len(args) == 2:
2724 ini,fin = args
2725 else:
2726 self.arg_err(Magic.magic_dhist)
2727 return
2728 else:
2729 ini,fin = 0,len(dh)
2730 nlprint(dh,
2731 header = 'Directory history (kept in _dh)',
2732 start=ini,stop=fin)
2733
2734
2569 2735 def magic_sc(self, parameter_s=''):
2570 2736 """Shell capture - execute a shell command and capture its output.
2571 2737
2572 2738 DEPRECATED. Suboptimal, retained for backwards compatibility.
2573 2739
2574 2740 You should use the form 'var = !command' instead. Example:
2575 2741
2576 2742 "%sc -l myfiles = ls ~" should now be written as
2577 2743
2578 2744 "myfiles = !ls ~"
2579 2745
2580 2746 myfiles.s, myfiles.l and myfiles.n still apply as documented
2581 2747 below.
2582 2748
2583 2749 --
2584 2750 %sc [options] varname=command
2585 2751
2586 2752 IPython will run the given command using commands.getoutput(), and
2587 2753 will then update the user's interactive namespace with a variable
2588 2754 called varname, containing the value of the call. Your command can
2589 2755 contain shell wildcards, pipes, etc.
2590 2756
2591 2757 The '=' sign in the syntax is mandatory, and the variable name you
2592 2758 supply must follow Python's standard conventions for valid names.
2593 2759
2594 2760 (A special format without variable name exists for internal use)
2595 2761
2596 2762 Options:
2597 2763
2598 2764 -l: list output. Split the output on newlines into a list before
2599 2765 assigning it to the given variable. By default the output is stored
2600 2766 as a single string.
2601 2767
2602 2768 -v: verbose. Print the contents of the variable.
2603 2769
2604 2770 In most cases you should not need to split as a list, because the
2605 2771 returned value is a special type of string which can automatically
2606 2772 provide its contents either as a list (split on newlines) or as a
2607 2773 space-separated string. These are convenient, respectively, either
2608 2774 for sequential processing or to be passed to a shell command.
2609 2775
2610 2776 For example:
2611 2777
2612 2778 # Capture into variable a
2613 2779 In [9]: sc a=ls *py
2614 2780
2615 2781 # a is a string with embedded newlines
2616 2782 In [10]: a
2617 2783 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2618 2784
2619 2785 # which can be seen as a list:
2620 2786 In [11]: a.l
2621 2787 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2622 2788
2623 2789 # or as a whitespace-separated string:
2624 2790 In [12]: a.s
2625 2791 Out[12]: 'setup.py win32_manual_post_install.py'
2626 2792
2627 2793 # a.s is useful to pass as a single command line:
2628 2794 In [13]: !wc -l $a.s
2629 2795 146 setup.py
2630 2796 130 win32_manual_post_install.py
2631 2797 276 total
2632 2798
2633 2799 # while the list form is useful to loop over:
2634 2800 In [14]: for f in a.l:
2635 2801 ....: !wc -l $f
2636 2802 ....:
2637 2803 146 setup.py
2638 2804 130 win32_manual_post_install.py
2639 2805
2640 2806 Similiarly, the lists returned by the -l option are also special, in
2641 2807 the sense that you can equally invoke the .s attribute on them to
2642 2808 automatically get a whitespace-separated string from their contents:
2643 2809
2644 2810 In [1]: sc -l b=ls *py
2645 2811
2646 2812 In [2]: b
2647 2813 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2648 2814
2649 2815 In [3]: b.s
2650 2816 Out[3]: 'setup.py win32_manual_post_install.py'
2651 2817
2652 2818 In summary, both the lists and strings used for ouptut capture have
2653 2819 the following special attributes:
2654 2820
2655 2821 .l (or .list) : value as list.
2656 2822 .n (or .nlstr): value as newline-separated string.
2657 2823 .s (or .spstr): value as space-separated string.
2658 2824 """
2659 2825
2660 2826 opts,args = self.parse_options(parameter_s,'lv')
2661 2827 # Try to get a variable name and command to run
2662 2828 try:
2663 2829 # the variable name must be obtained from the parse_options
2664 2830 # output, which uses shlex.split to strip options out.
2665 2831 var,_ = args.split('=',1)
2666 2832 var = var.strip()
2667 2833 # But the the command has to be extracted from the original input
2668 2834 # parameter_s, not on what parse_options returns, to avoid the
2669 2835 # quote stripping which shlex.split performs on it.
2670 2836 _,cmd = parameter_s.split('=',1)
2671 2837 except ValueError:
2672 2838 var,cmd = '',''
2673 2839 # If all looks ok, proceed
2674 2840 out,err = self.shell.getoutputerror(cmd)
2675 2841 if err:
2676 2842 print >> Term.cerr,err
2677 2843 if opts.has_key('l'):
2678 2844 out = SList(out.split('\n'))
2679 2845 else:
2680 2846 out = LSString(out)
2681 2847 if opts.has_key('v'):
2682 2848 print '%s ==\n%s' % (var,pformat(out))
2683 2849 if var:
2684 2850 self.shell.user_ns.update({var:out})
2685 2851 else:
2686 2852 return out
2687 2853
2688 2854 def magic_sx(self, parameter_s=''):
2689 2855 """Shell execute - run a shell command and capture its output.
2690 2856
2691 2857 %sx command
2692 2858
2693 2859 IPython will run the given command using commands.getoutput(), and
2694 2860 return the result formatted as a list (split on '\\n'). Since the
2695 2861 output is _returned_, it will be stored in ipython's regular output
2696 2862 cache Out[N] and in the '_N' automatic variables.
2697 2863
2698 2864 Notes:
2699 2865
2700 2866 1) If an input line begins with '!!', then %sx is automatically
2701 2867 invoked. That is, while:
2702 2868 !ls
2703 2869 causes ipython to simply issue system('ls'), typing
2704 2870 !!ls
2705 2871 is a shorthand equivalent to:
2706 2872 %sx ls
2707 2873
2708 2874 2) %sx differs from %sc in that %sx automatically splits into a list,
2709 2875 like '%sc -l'. The reason for this is to make it as easy as possible
2710 2876 to process line-oriented shell output via further python commands.
2711 2877 %sc is meant to provide much finer control, but requires more
2712 2878 typing.
2713 2879
2714 2880 3) Just like %sc -l, this is a list with special attributes:
2715 2881
2716 2882 .l (or .list) : value as list.
2717 2883 .n (or .nlstr): value as newline-separated string.
2718 2884 .s (or .spstr): value as whitespace-separated string.
2719 2885
2720 2886 This is very useful when trying to use such lists as arguments to
2721 2887 system commands."""
2722 2888
2723 2889 if parameter_s:
2724 2890 out,err = self.shell.getoutputerror(parameter_s)
2725 2891 if err:
2726 2892 print >> Term.cerr,err
2727 2893 return SList(out.split('\n'))
2728 2894
2729 2895 def magic_bg(self, parameter_s=''):
2730 2896 """Run a job in the background, in a separate thread.
2731 2897
2732 2898 For example,
2733 2899
2734 2900 %bg myfunc(x,y,z=1)
2735 2901
2736 2902 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2737 2903 execution starts, a message will be printed indicating the job
2738 2904 number. If your job number is 5, you can use
2739 2905
2740 2906 myvar = jobs.result(5) or myvar = jobs[5].result
2741 2907
2742 2908 to assign this result to variable 'myvar'.
2743 2909
2744 2910 IPython has a job manager, accessible via the 'jobs' object. You can
2745 2911 type jobs? to get more information about it, and use jobs.<TAB> to see
2746 2912 its attributes. All attributes not starting with an underscore are
2747 2913 meant for public use.
2748 2914
2749 2915 In particular, look at the jobs.new() method, which is used to create
2750 2916 new jobs. This magic %bg function is just a convenience wrapper
2751 2917 around jobs.new(), for expression-based jobs. If you want to create a
2752 2918 new job with an explicit function object and arguments, you must call
2753 2919 jobs.new() directly.
2754 2920
2755 2921 The jobs.new docstring also describes in detail several important
2756 2922 caveats associated with a thread-based model for background job
2757 2923 execution. Type jobs.new? for details.
2758 2924
2759 2925 You can check the status of all jobs with jobs.status().
2760 2926
2761 2927 The jobs variable is set by IPython into the Python builtin namespace.
2762 2928 If you ever declare a variable named 'jobs', you will shadow this
2763 2929 name. You can either delete your global jobs variable to regain
2764 2930 access to the job manager, or make a new name and assign it manually
2765 2931 to the manager (stored in IPython's namespace). For example, to
2766 2932 assign the job manager to the Jobs name, use:
2767 2933
2768 2934 Jobs = __builtins__.jobs"""
2769 2935
2770 2936 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2771 2937
2938 def magic_r(self, parameter_s=''):
2939 """Repeat previous input.
2940
2941 If given an argument, repeats the previous command which starts with
2942 the same string, otherwise it just repeats the previous input.
2943
2944 Shell escaped commands (with ! as first character) are not recognized
2945 by this system, only pure python code and magic commands.
2946 """
2947
2948 start = parameter_s.strip()
2949 esc_magic = self.shell.ESC_MAGIC
2950 # Identify magic commands even if automagic is on (which means
2951 # the in-memory version is different from that typed by the user).
2952 if self.shell.rc.automagic:
2953 start_magic = esc_magic+start
2954 else:
2955 start_magic = start
2956 # Look through the input history in reverse
2957 for n in range(len(self.shell.input_hist)-2,0,-1):
2958 input = self.shell.input_hist[n]
2959 # skip plain 'r' lines so we don't recurse to infinity
2960 if input != '_ip.magic("r")\n' and \
2961 (input.startswith(start) or input.startswith(start_magic)):
2962 #print 'match',`input` # dbg
2963 print 'Executing:',input,
2964 self.shell.runlines(input)
2965 return
2966 print 'No previous input matching `%s` found.' % start
2967
2772 2968
2773 2969 def magic_bookmark(self, parameter_s=''):
2774 2970 """Manage IPython's bookmark system.
2775 2971
2776 2972 %bookmark <name> - set bookmark to current dir
2777 2973 %bookmark <name> <dir> - set bookmark to <dir>
2778 2974 %bookmark -l - list all bookmarks
2779 2975 %bookmark -d <name> - remove bookmark
2780 2976 %bookmark -r - remove all bookmarks
2781 2977
2782 2978 You can later on access a bookmarked folder with:
2783 2979 %cd -b <name>
2784 2980 or simply '%cd <name>' if there is no directory called <name> AND
2785 2981 there is such a bookmark defined.
2786 2982
2787 2983 Your bookmarks persist through IPython sessions, but they are
2788 2984 associated with each profile."""
2789 2985
2790 2986 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2791 2987 if len(args) > 2:
2792 2988 error('You can only give at most two arguments')
2793 2989 return
2794 2990
2795 2991 bkms = self.db.get('bookmarks',{})
2796 2992
2797 2993 if opts.has_key('d'):
2798 2994 try:
2799 2995 todel = args[0]
2800 2996 except IndexError:
2801 2997 error('You must provide a bookmark to delete')
2802 2998 else:
2803 2999 try:
2804 3000 del bkms[todel]
2805 3001 except:
2806 3002 error("Can't delete bookmark '%s'" % todel)
2807 3003 elif opts.has_key('r'):
2808 3004 bkms = {}
2809 3005 elif opts.has_key('l'):
2810 3006 bks = bkms.keys()
2811 3007 bks.sort()
2812 3008 if bks:
2813 3009 size = max(map(len,bks))
2814 3010 else:
2815 3011 size = 0
2816 3012 fmt = '%-'+str(size)+'s -> %s'
2817 3013 print 'Current bookmarks:'
2818 3014 for bk in bks:
2819 3015 print fmt % (bk,bkms[bk])
2820 3016 else:
2821 3017 if not args:
2822 3018 error("You must specify the bookmark name")
2823 3019 elif len(args)==1:
2824 3020 bkms[args[0]] = os.getcwd()
2825 3021 elif len(args)==2:
2826 3022 bkms[args[0]] = args[1]
2827 3023 self.db['bookmarks'] = bkms
2828 3024
2829 3025 def magic_pycat(self, parameter_s=''):
2830 3026 """Show a syntax-highlighted file through a pager.
2831 3027
2832 3028 This magic is similar to the cat utility, but it will assume the file
2833 3029 to be Python source and will show it with syntax highlighting. """
2834 3030
2835 3031 try:
2836 3032 filename = get_py_filename(parameter_s)
2837 3033 cont = file_read(filename)
2838 3034 except IOError:
2839 3035 try:
2840 3036 cont = eval(parameter_s,self.user_ns)
2841 3037 except NameError:
2842 3038 cont = None
2843 3039 if cont is None:
2844 3040 print "Error: no such file or variable"
2845 3041 return
2846 3042
2847 3043 page(self.shell.pycolorize(cont),
2848 3044 screen_lines=self.shell.rc.screen_length)
2849 3045
2850 3046 def magic_cpaste(self, parameter_s=''):
2851 3047 """Allows you to paste & execute a pre-formatted code block from clipboard
2852 3048
2853 3049 You must terminate the block with '--' (two minus-signs) alone on the
2854 3050 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2855 3051 is the new sentinel for this operation)
2856 3052
2857 3053 The block is dedented prior to execution to enable execution of method
2858 3054 definitions. '>' and '+' characters at the beginning of a line are
2859 3055 ignored, to allow pasting directly from e-mails or diff files. The
2860 3056 executed block is also assigned to variable named 'pasted_block' for
2861 3057 later editing with '%edit pasted_block'.
2862 3058
2863 3059 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2864 3060 This assigns the pasted block to variable 'foo' as string, without
2865 3061 dedenting or executing it.
2866 3062
2867 3063 Do not be alarmed by garbled output on Windows (it's a readline bug).
2868 3064 Just press enter and type -- (and press enter again) and the block
2869 3065 will be what was just pasted.
2870 3066
2871 3067 IPython statements (magics, shell escapes) are not supported (yet).
2872 3068 """
2873 3069 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2874 3070 par = args.strip()
2875 3071 sentinel = opts.get('s','--')
2876 3072
2877 3073 from IPython import iplib
2878 3074 lines = []
2879 3075 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2880 3076 while 1:
2881 3077 l = iplib.raw_input_original(':')
2882 3078 if l ==sentinel:
2883 3079 break
2884 3080 lines.append(l.lstrip('>').lstrip('+'))
2885 3081 block = "\n".join(lines) + '\n'
2886 3082 #print "block:\n",block
2887 3083 if not par:
2888 3084 b = textwrap.dedent(block)
2889 3085 exec b in self.user_ns
2890 3086 self.user_ns['pasted_block'] = b
2891 3087 else:
2892 3088 self.user_ns[par] = block
2893 3089 print "Block assigned to '%s'" % par
2894 3090
2895 3091 def magic_quickref(self,arg):
2896 3092 """ Show a quick reference sheet """
2897 3093 import IPython.usage
2898 3094 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2899 3095
2900 3096 page(qr)
2901 3097
2902 3098 def magic_upgrade(self,arg):
2903 3099 """ Upgrade your IPython installation
2904 3100
2905 3101 This will copy the config files that don't yet exist in your
2906 3102 ipython dir from the system config dir. Use this after upgrading
2907 3103 IPython if you don't wish to delete your .ipython dir.
2908 3104
2909 3105 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2910 3106 new users)
2911 3107
2912 3108 """
2913 3109 ip = self.getapi()
2914 3110 ipinstallation = path(IPython.__file__).dirname()
2915 3111 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
2916 3112 src_config = ipinstallation / 'UserConfig'
2917 3113 userdir = path(ip.options.ipythondir)
2918 3114 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
2919 3115 print ">",cmd
2920 3116 shell(cmd)
2921 3117 if arg == '-nolegacy':
2922 3118 legacy = userdir.files('ipythonrc*')
2923 3119 print "Nuking legacy files:",legacy
2924 3120
2925 3121 [p.remove() for p in legacy]
2926 3122 suffix = (sys.platform == 'win32' and '.ini' or '')
2927 3123 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2928 3124
2929 3125
2930 3126 def magic_doctest_mode(self,parameter_s=''):
2931 3127 """Toggle doctest mode on and off.
2932 3128
2933 3129 This mode allows you to toggle the prompt behavior between normal
2934 3130 IPython prompts and ones that are as similar to the default IPython
2935 3131 interpreter as possible.
2936 3132
2937 3133 It also supports the pasting of code snippets that have leading '>>>'
2938 3134 and '...' prompts in them. This means that you can paste doctests from
2939 3135 files or docstrings (even if they have leading whitespace), and the
2940 3136 code will execute correctly. You can then use '%history -tn' to see
2941 3137 the translated history without line numbers; this will give you the
2942 3138 input after removal of all the leading prompts and whitespace, which
2943 3139 can be pasted back into an editor.
2944 3140
2945 3141 With these features, you can switch into this mode easily whenever you
2946 3142 need to do testing and changes to doctests, without having to leave
2947 3143 your existing IPython session.
2948 3144 """
2949 3145
2950 3146 # XXX - Fix this to have cleaner activate/deactivate calls.
2951 3147 from IPython.Extensions import InterpreterPasteInput as ipaste
2952 3148 from IPython.ipstruct import Struct
2953 3149
2954 3150 # Shorthands
2955 3151 shell = self.shell
2956 3152 oc = shell.outputcache
2957 3153 rc = shell.rc
2958 3154 meta = shell.meta
2959 3155 # dstore is a data store kept in the instance metadata bag to track any
2960 3156 # changes we make, so we can undo them later.
2961 3157 dstore = meta.setdefault('doctest_mode',Struct())
2962 3158 save_dstore = dstore.setdefault
2963 3159
2964 3160 # save a few values we'll need to recover later
2965 3161 mode = save_dstore('mode',False)
2966 3162 save_dstore('rc_pprint',rc.pprint)
2967 3163 save_dstore('xmode',shell.InteractiveTB.mode)
2968 3164 save_dstore('rc_separate_in',rc.separate_in)
2969 3165 save_dstore('rc_separate_out',rc.separate_out)
2970 3166 save_dstore('rc_separate_out2',rc.separate_out2)
2971 3167 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
2972 3168
2973 3169 if mode == False:
2974 3170 # turn on
2975 3171 ipaste.activate_prefilter()
2976 3172
2977 3173 oc.prompt1.p_template = '>>> '
2978 3174 oc.prompt2.p_template = '... '
2979 3175 oc.prompt_out.p_template = ''
2980 3176
2981 3177 oc.prompt1.sep = '\n'
2982 3178 oc.output_sep = ''
2983 3179 oc.output_sep2 = ''
2984 3180
2985 3181 oc.prompt1.pad_left = oc.prompt2.pad_left = \
2986 3182 oc.prompt_out.pad_left = False
2987 3183
2988 3184 rc.pprint = False
2989 3185
2990 3186 shell.magic_xmode('Plain')
2991 3187
2992 3188 else:
2993 3189 # turn off
2994 3190 ipaste.deactivate_prefilter()
2995 3191
2996 3192 oc.prompt1.p_template = rc.prompt_in1
2997 3193 oc.prompt2.p_template = rc.prompt_in2
2998 3194 oc.prompt_out.p_template = rc.prompt_out
2999 3195
3000 3196 oc.prompt1.sep = dstore.rc_separate_in
3001 3197 oc.output_sep = dstore.rc_separate_out
3002 3198 oc.output_sep2 = dstore.rc_separate_out2
3003 3199
3004 3200 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3005 3201 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3006 3202
3007 3203 rc.pprint = dstore.rc_pprint
3008 3204
3009 3205 shell.magic_xmode(dstore.xmode)
3010 3206
3011 3207 # Store new mode and inform
3012 3208 dstore.mode = bool(1-int(mode))
3013 3209 print 'Doctest mode is:',
3014 3210 print ['OFF','ON'][dstore.mode]
3015 3211
3016 3212 # end Magic
@@ -1,579 +1,577 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8
9 $Id: OInspect.py 2717 2007-09-05 19:49:42Z vivainio $
9 $Id: OInspect.py 2723 2007-09-07 07:44:16Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #*****************************************************************************
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 21 __license__ = Release.license
22 22
23 23 __all__ = ['Inspector','InspectColors']
24 24
25 25 # stdlib modules
26 26 import __builtin__
27 27 import inspect
28 28 import linecache
29 29 import string
30 30 import StringIO
31 31 import types
32 32 import os
33 33 import sys
34 34 # IPython's own
35 35 from IPython import PyColorize
36 36 from IPython.genutils import page,indent,Term,mkdict
37 37 from IPython.Itpl import itpl
38 38 from IPython.wildcard import list_namespace
39 39 from IPython.ColorANSI import *
40 40
41 41 #****************************************************************************
42 42 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
43 43 # simply monkeypatch inspect with code copied from python 2.4.
44 44 if sys.version_info[:2] == (2,3):
45 45 from inspect import ismodule, getabsfile, modulesbyfile
46 46 def getmodule(object):
47 47 """Return the module an object was defined in, or None if not found."""
48 48 if ismodule(object):
49 49 return object
50 50 if hasattr(object, '__module__'):
51 51 return sys.modules.get(object.__module__)
52 52 try:
53 53 file = getabsfile(object)
54 54 except TypeError:
55 55 return None
56 56 if file in modulesbyfile:
57 57 return sys.modules.get(modulesbyfile[file])
58 58 for module in sys.modules.values():
59 59 if hasattr(module, '__file__'):
60 60 modulesbyfile[
61 61 os.path.realpath(
62 62 getabsfile(module))] = module.__name__
63 63 if file in modulesbyfile:
64 64 return sys.modules.get(modulesbyfile[file])
65 65 main = sys.modules['__main__']
66 66 if not hasattr(object, '__name__'):
67 67 return None
68 68 if hasattr(main, object.__name__):
69 69 mainobject = getattr(main, object.__name__)
70 70 if mainobject is object:
71 71 return main
72 72 builtin = sys.modules['__builtin__']
73 73 if hasattr(builtin, object.__name__):
74 74 builtinobject = getattr(builtin, object.__name__)
75 75 if builtinobject is object:
76 76 return builtin
77 77
78 78 inspect.getmodule = getmodule
79 79
80 80 #****************************************************************************
81 81 # Builtin color schemes
82 82
83 83 Colors = TermColors # just a shorthand
84 84
85 85 # Build a few color schemes
86 86 NoColor = ColorScheme(
87 87 'NoColor',{
88 88 'header' : Colors.NoColor,
89 89 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
90 90 } )
91 91
92 92 LinuxColors = ColorScheme(
93 93 'Linux',{
94 94 'header' : Colors.LightRed,
95 95 'normal' : Colors.Normal # color off (usu. Colors.Normal)
96 96 } )
97 97
98 98 LightBGColors = ColorScheme(
99 99 'LightBG',{
100 100 'header' : Colors.Red,
101 101 'normal' : Colors.Normal # color off (usu. Colors.Normal)
102 102 } )
103 103
104 104 # Build table of color schemes (needed by the parser)
105 105 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
106 106 'Linux')
107 107
108 108 #****************************************************************************
109 109 # Auxiliary functions
110 110 def getdoc(obj):
111 111 """Stable wrapper around inspect.getdoc.
112 112
113 113 This can't crash because of attribute problems.
114 114
115 115 It also attempts to call a getdoc() method on the given object. This
116 116 allows objects which provide their docstrings via non-standard mechanisms
117 117 (like Pyro proxies) to still be inspected by ipython's ? system."""
118 118
119 119 ds = None # default return value
120 120 try:
121 121 ds = inspect.getdoc(obj)
122 122 except:
123 123 # Harden against an inspect failure, which can occur with
124 124 # SWIG-wrapped extensions.
125 125 pass
126 126 # Allow objects to offer customized documentation via a getdoc method:
127 127 try:
128 128 ds2 = obj.getdoc()
129 129 except:
130 130 pass
131 131 else:
132 132 # if we get extra info, we add it to the normal docstring.
133 133 if ds is None:
134 134 ds = ds2
135 135 else:
136 136 ds = '%s\n%s' % (ds,ds2)
137 137 return ds
138 138
139 139 def getsource(obj,is_binary=False):
140 140 """Wrapper around inspect.getsource.
141 141
142 142 This can be modified by other projects to provide customized source
143 143 extraction.
144 144
145 145 Inputs:
146 146
147 147 - obj: an object whose source code we will attempt to extract.
148 148
149 149 Optional inputs:
150 150
151 151 - is_binary: whether the object is known to come from a binary source.
152 152 This implementation will skip returning any output for binary objects, but
153 153 custom extractors may know how to meaningfully process them."""
154 154
155 155 if is_binary:
156 156 return None
157 157 else:
158 158 return inspect.getsource(obj)
159 159
160 160 #****************************************************************************
161 161 # Class definitions
162 162
163 163 class myStringIO(StringIO.StringIO):
164 164 """Adds a writeln method to normal StringIO."""
165 165 def writeln(self,*arg,**kw):
166 166 """Does a write() and then a write('\n')"""
167 167 self.write(*arg,**kw)
168 168 self.write('\n')
169 169
170 170 class Inspector:
171 171 def __init__(self,color_table,code_color_table,scheme,
172 172 str_detail_level=0):
173 173 self.color_table = color_table
174 174 self.parser = PyColorize.Parser(code_color_table,out='str')
175 175 self.format = self.parser.format
176 176 self.str_detail_level = str_detail_level
177 177 self.set_active_scheme(scheme)
178 178
179 179 def __getargspec(self,obj):
180 180 """Get the names and default values of a function's arguments.
181 181
182 182 A tuple of four things is returned: (args, varargs, varkw, defaults).
183 183 'args' is a list of the argument names (it may contain nested lists).
184 184 'varargs' and 'varkw' are the names of the * and ** arguments or None.
185 185 'defaults' is an n-tuple of the default values of the last n arguments.
186 186
187 187 Modified version of inspect.getargspec from the Python Standard
188 188 Library."""
189 189
190 190 if inspect.isfunction(obj):
191 191 func_obj = obj
192 192 elif inspect.ismethod(obj):
193 193 func_obj = obj.im_func
194 194 else:
195 195 raise TypeError, 'arg is not a Python function'
196 196 args, varargs, varkw = inspect.getargs(func_obj.func_code)
197 197 return args, varargs, varkw, func_obj.func_defaults
198 198
199 199 def __getdef(self,obj,oname=''):
200 200 """Return the definition header for any callable object.
201 201
202 202 If any exception is generated, None is returned instead and the
203 203 exception is suppressed."""
204 204
205 205 try:
206 206 return oname + inspect.formatargspec(*self.__getargspec(obj))
207 207 except:
208 208 return None
209 209
210 210 def __head(self,h):
211 211 """Return a header string with proper colors."""
212 212 return '%s%s%s' % (self.color_table.active_colors.header,h,
213 213 self.color_table.active_colors.normal)
214 214
215 215 def set_active_scheme(self,scheme):
216 216 self.color_table.set_active_scheme(scheme)
217 217 self.parser.color_table.set_active_scheme(scheme)
218 218
219 219 def noinfo(self,msg,oname):
220 220 """Generic message when no information is found."""
221 221 print 'No %s found' % msg,
222 222 if oname:
223 223 print 'for %s' % oname
224 224 else:
225 225 print
226 226
227 227 def pdef(self,obj,oname=''):
228 228 """Print the definition header for any callable object.
229 229
230 230 If the object is a class, print the constructor information."""
231 231
232 232 if not callable(obj):
233 233 print 'Object is not callable.'
234 234 return
235 235
236 236 header = ''
237 237
238 238 if inspect.isclass(obj):
239 239 header = self.__head('Class constructor information:\n')
240 240 obj = obj.__init__
241 elif type(obj) is types.InstanceType or \
242 isinstance(obj,object):
241 elif type(obj) is types.InstanceType:
243 242 obj = obj.__call__
244 243
245 244 output = self.__getdef(obj,oname)
246 245 if output is None:
247 246 self.noinfo('definition header',oname)
248 247 else:
249 248 print >>Term.cout, header,self.format(output),
250 249
251 250 def pdoc(self,obj,oname='',formatter = None):
252 251 """Print the docstring for any object.
253 252
254 253 Optional:
255 254 -formatter: a function to run the docstring through for specially
256 255 formatted docstrings."""
257 256
258 257 head = self.__head # so that itpl can find it even if private
259 258 ds = getdoc(obj)
260 259 if formatter:
261 260 ds = formatter(ds)
262 261 if inspect.isclass(obj):
263 262 init_ds = getdoc(obj.__init__)
264 263 output = itpl('$head("Class Docstring:")\n'
265 264 '$indent(ds)\n'
266 265 '$head("Constructor Docstring"):\n'
267 266 '$indent(init_ds)')
268 267 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
269 268 and hasattr(obj,'__call__'):
270 269 call_ds = getdoc(obj.__call__)
271 270 if call_ds:
272 271 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
273 272 '$head("Calling Docstring:")\n$indent(call_ds)')
274 273 else:
275 274 output = ds
276 275 else:
277 276 output = ds
278 277 if output is None:
279 278 self.noinfo('documentation',oname)
280 279 return
281 280 page(output)
282 281
283 282 def psource(self,obj,oname=''):
284 283 """Print the source code for an object."""
285 284
286 285 # Flush the source cache because inspect can return out-of-date source
287 286 linecache.checkcache()
288 287 try:
289 288 src = getsource(obj)
290 289 except:
291 290 self.noinfo('source',oname)
292 291 else:
293 292 page(self.format(src))
294 293
295 294 def pfile(self,obj,oname=''):
296 295 """Show the whole file where an object was defined."""
297 296 try:
298 297 sourcelines,lineno = inspect.getsourcelines(obj)
299 298 except:
300 299 self.noinfo('file',oname)
301 300 else:
302 301 # run contents of file through pager starting at line
303 302 # where the object is defined
304 303 ofile = inspect.getabsfile(obj)
305 304
306 305 if (ofile.endswith('.so') or ofile.endswith('.dll')):
307 306 print 'File %r is binary, not printing.' % ofile
308 307 elif not os.path.isfile(ofile):
309 308 print 'File %r does not exist, not printing.' % ofile
310 309 else:
311 310 # Print only text files, not extension binaries.
312 311 page(self.format(open(ofile).read()),lineno)
313 312 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
314 313
315 314 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
316 315 """Show detailed information about an object.
317 316
318 317 Optional arguments:
319 318
320 319 - oname: name of the variable pointing to the object.
321 320
322 321 - formatter: special formatter for docstrings (see pdoc)
323 322
324 323 - info: a structure with some information fields which may have been
325 324 precomputed already.
326 325
327 326 - detail_level: if set to 1, more information is given.
328 327 """
329 328
330 329 obj_type = type(obj)
331 330
332 331 header = self.__head
333 332 if info is None:
334 333 ismagic = 0
335 334 isalias = 0
336 335 ospace = ''
337 336 else:
338 337 ismagic = info.ismagic
339 338 isalias = info.isalias
340 339 ospace = info.namespace
341 340 # Get docstring, special-casing aliases:
342 341 if isalias:
343 342 if not callable(obj):
344 343 try:
345 344 ds = "Alias to the system command:\n %s" % obj[1]
346 345 except:
347 346 ds = "Alias: " + str(obj)
348 347 else:
349 348 ds = "Alias to " + str(obj)
350 349 if obj.__doc__:
351 350 ds += "\nDocstring:\n" + obj.__doc__
352 351 else:
353 352 ds = getdoc(obj)
354 353 if ds is None:
355 354 ds = '<no docstring>'
356 355 if formatter is not None:
357 356 ds = formatter(ds)
358 357
359 358 # store output in a list which gets joined with \n at the end.
360 359 out = myStringIO()
361 360
362 361 string_max = 200 # max size of strings to show (snipped if longer)
363 362 shalf = int((string_max -5)/2)
364 363
365 364 if ismagic:
366 365 obj_type_name = 'Magic function'
367 366 elif isalias:
368 367 obj_type_name = 'System alias'
369 368 else:
370 369 obj_type_name = obj_type.__name__
371 370 out.writeln(header('Type:\t\t')+obj_type_name)
372 371
373 372 try:
374 373 bclass = obj.__class__
375 374 out.writeln(header('Base Class:\t')+str(bclass))
376 375 except: pass
377 376
378 377 # String form, but snip if too long in ? form (full in ??)
379 378 if detail_level >= self.str_detail_level:
380 379 try:
381 380 ostr = str(obj)
382 381 str_head = 'String Form:'
383 382 if not detail_level and len(ostr)>string_max:
384 383 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
385 384 ostr = ("\n" + " " * len(str_head.expandtabs())).\
386 385 join(map(string.strip,ostr.split("\n")))
387 386 if ostr.find('\n') > -1:
388 387 # Print multi-line strings starting at the next line.
389 388 str_sep = '\n'
390 389 else:
391 390 str_sep = '\t'
392 391 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
393 392 except:
394 393 pass
395 394
396 395 if ospace:
397 396 out.writeln(header('Namespace:\t')+ospace)
398 397
399 398 # Length (for strings and lists)
400 399 try:
401 400 length = str(len(obj))
402 401 out.writeln(header('Length:\t\t')+length)
403 402 except: pass
404 403
405 404 # Filename where object was defined
406 405 binary_file = False
407 406 try:
408 407 fname = inspect.getabsfile(obj)
409 408 if fname.endswith('<string>'):
410 409 fname = 'Dynamically generated function. No source code available.'
411 if (fname.endswith('.so') or fname.endswith('.dll') or
412 not os.path.isfile(fname)):
410 if (fname.endswith('.so') or fname.endswith('.dll')):
413 411 binary_file = True
414 412 out.writeln(header('File:\t\t')+fname)
415 413 except:
416 414 # if anything goes wrong, we don't want to show source, so it's as
417 415 # if the file was binary
418 416 binary_file = True
419 417
420 418 # reconstruct the function definition and print it:
421 419 defln = self.__getdef(obj,oname)
422 420 if defln:
423 421 out.write(header('Definition:\t')+self.format(defln))
424 422
425 423 # Docstrings only in detail 0 mode, since source contains them (we
426 424 # avoid repetitions). If source fails, we add them back, see below.
427 425 if ds and detail_level == 0:
428 426 out.writeln(header('Docstring:\n') + indent(ds))
429
430 427
431 428 # Original source code for any callable
432 429 if detail_level:
433 # Flush the source cache because inspect can return out-of-date source
430 # Flush the source cache because inspect can return out-of-date
431 # source
434 432 linecache.checkcache()
435 433 source_success = False
436 434 try:
437 435 source = self.format(getsource(obj,binary_file))
438 436 if source:
439 437 out.write(header('Source:\n')+source.rstrip())
440 438 source_success = True
441 439 except Exception, msg:
442 440 pass
443 441
444 442 if ds and not source_success:
445 443 out.writeln(header('Docstring [source file open failed]:\n')
446 444 + indent(ds))
447 445
448 446 # Constructor docstring for classes
449 447 if inspect.isclass(obj):
450 448 # reconstruct the function definition and print it:
451 449 try:
452 450 obj_init = obj.__init__
453 451 except AttributeError:
454 452 init_def = init_ds = None
455 453 else:
456 454 init_def = self.__getdef(obj_init,oname)
457 455 init_ds = getdoc(obj_init)
458 456 # Skip Python's auto-generated docstrings
459 457 if init_ds and \
460 458 init_ds.startswith('x.__init__(...) initializes'):
461 459 init_ds = None
462 460
463 461 if init_def or init_ds:
464 462 out.writeln(header('\nConstructor information:'))
465 463 if init_def:
466 464 out.write(header('Definition:\t')+ self.format(init_def))
467 465 if init_ds:
468 466 out.writeln(header('Docstring:\n') + indent(init_ds))
469 467 # and class docstring for instances:
470 468 elif obj_type is types.InstanceType or \
471 469 isinstance(obj,object):
472 470
473 471 # First, check whether the instance docstring is identical to the
474 472 # class one, and print it separately if they don't coincide. In
475 473 # most cases they will, but it's nice to print all the info for
476 474 # objects which use instance-customized docstrings.
477 475 if ds:
478 476 class_ds = getdoc(obj.__class__)
479 477 # Skip Python's auto-generated docstrings
480 478 if class_ds and \
481 479 (class_ds.startswith('function(code, globals[,') or \
482 480 class_ds.startswith('instancemethod(function, instance,') or \
483 481 class_ds.startswith('module(name[,') ):
484 482 class_ds = None
485 483 if class_ds and ds != class_ds:
486 484 out.writeln(header('Class Docstring:\n') +
487 485 indent(class_ds))
488 486
489 487 # Next, try to show constructor docstrings
490 488 try:
491 489 init_ds = getdoc(obj.__init__)
492 490 # Skip Python's auto-generated docstrings
493 491 if init_ds and \
494 492 init_ds.startswith('x.__init__(...) initializes'):
495 493 init_ds = None
496 494 except AttributeError:
497 495 init_ds = None
498 496 if init_ds:
499 497 out.writeln(header('Constructor Docstring:\n') +
500 498 indent(init_ds))
501 499
502 500 # Call form docstring for callable instances
503 501 if hasattr(obj,'__call__'):
504 502 #out.writeln(header('Callable:\t')+'Yes')
505 503 call_def = self.__getdef(obj.__call__,oname)
506 504 #if call_def is None:
507 505 # out.writeln(header('Call def:\t')+
508 506 # 'Calling definition not available.')
509 507 if call_def is not None:
510 508 out.writeln(header('Call def:\t')+self.format(call_def))
511 509 call_ds = getdoc(obj.__call__)
512 510 # Skip Python's auto-generated docstrings
513 511 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
514 512 call_ds = None
515 513 if call_ds:
516 514 out.writeln(header('Call docstring:\n') + indent(call_ds))
517 515
518 516 # Finally send to printer/pager
519 517 output = out.getvalue()
520 518 if output:
521 519 page(output)
522 520 # end pinfo
523 521
524 522 def psearch(self,pattern,ns_table,ns_search=[],
525 523 ignore_case=False,show_all=False):
526 524 """Search namespaces with wildcards for objects.
527 525
528 526 Arguments:
529 527
530 528 - pattern: string containing shell-like wildcards to use in namespace
531 529 searches and optionally a type specification to narrow the search to
532 530 objects of that type.
533 531
534 532 - ns_table: dict of name->namespaces for search.
535 533
536 534 Optional arguments:
537 535
538 536 - ns_search: list of namespace names to include in search.
539 537
540 538 - ignore_case(False): make the search case-insensitive.
541 539
542 540 - show_all(False): show all names, including those starting with
543 541 underscores.
544 542 """
545 543 #print 'ps pattern:<%r>' % pattern # dbg
546 544
547 545 # defaults
548 546 type_pattern = 'all'
549 547 filter = ''
550 548
551 549 cmds = pattern.split()
552 550 len_cmds = len(cmds)
553 551 if len_cmds == 1:
554 552 # Only filter pattern given
555 553 filter = cmds[0]
556 554 elif len_cmds == 2:
557 555 # Both filter and type specified
558 556 filter,type_pattern = cmds
559 557 else:
560 558 raise ValueError('invalid argument string for psearch: <%s>' %
561 559 pattern)
562 560
563 561 # filter search namespaces
564 562 for name in ns_search:
565 563 if name not in ns_table:
566 564 raise ValueError('invalid namespace <%s>. Valid names: %s' %
567 565 (name,ns_table.keys()))
568 566
569 567 #print 'type_pattern:',type_pattern # dbg
570 568 search_result = []
571 569 for ns_name in ns_search:
572 570 ns = ns_table[ns_name]
573 571 tmp_res = list(list_namespace(ns,type_pattern,filter,
574 572 ignore_case=ignore_case,
575 573 show_all=show_all))
576 574 search_result.extend(tmp_res)
577 575 search_result.sort()
578 576
579 577 page('\n'.join(search_result))
@@ -1,763 +1,763 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 2710 2007-09-04 21:10:10Z vivainio $"""
9 $Id: ipmaker.py 2723 2007-09-07 07:44:16Z fperez $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 try:
24 24 credits._Printer__data = """
25 25 Python: %s
26 26
27 27 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
28 28 See http://ipython.scipy.org for more information.""" \
29 29 % credits._Printer__data
30 30
31 31 copyright._Printer__data += """
32 32
33 33 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
34 34 All Rights Reserved."""
35 35 except NameError:
36 36 # Can happen if ipython was started with 'python -S', so that site.py is
37 37 # not loaded
38 38 pass
39 39
40 40 #****************************************************************************
41 41 # Required modules
42 42
43 43 # From the standard library
44 44 import __main__
45 45 import __builtin__
46 46 import os
47 47 import re
48 48 import sys
49 49 import types
50 50 from pprint import pprint,pformat
51 51
52 52 # Our own
53 53 from IPython import DPyGetOpt
54 54 from IPython.ipstruct import Struct
55 55 from IPython.OutputTrap import OutputTrap
56 56 from IPython.ConfigLoader import ConfigLoader
57 57 from IPython.iplib import InteractiveShell
58 58 from IPython.usage import cmd_line_usage,interactive_usage
59 59 from IPython.genutils import *
60 60
61 61 #-----------------------------------------------------------------------------
62 62 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
63 63 rc_override=None,shell_class=InteractiveShell,
64 64 embedded=False,**kw):
65 65 """This is a dump of IPython into a single function.
66 66
67 67 Later it will have to be broken up in a sensible manner.
68 68
69 69 Arguments:
70 70
71 71 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
72 72 script name, b/c DPyGetOpt strips the first argument only for the real
73 73 sys.argv.
74 74
75 75 - user_ns: a dict to be used as the user's namespace."""
76 76
77 77 #----------------------------------------------------------------------
78 78 # Defaults and initialization
79 79
80 80 # For developer debugging, deactivates crash handler and uses pdb.
81 81 DEVDEBUG = False
82 82
83 83 if argv is None:
84 84 argv = sys.argv
85 85
86 86 # __IP is the main global that lives throughout and represents the whole
87 87 # application. If the user redefines it, all bets are off as to what
88 88 # happens.
89 89
90 90 # __IP is the name of he global which the caller will have accessible as
91 91 # __IP.name. We set its name via the first parameter passed to
92 92 # InteractiveShell:
93 93
94 94 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
95 95 embedded=embedded,**kw)
96 96
97 97 # Put 'help' in the user namespace
98 98 from site import _Helper
99 99 IP.user_config_ns = {}
100 100 IP.user_ns['help'] = _Helper()
101 101
102 102
103 103 if DEVDEBUG:
104 104 # For developer debugging only (global flag)
105 105 from IPython import ultraTB
106 106 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
107 107
108 108 IP.BANNER_PARTS = ['Python %s\n'
109 109 'Type "copyright", "credits" or "license" '
110 110 'for more information.\n'
111 111 % (sys.version.split('\n')[0],),
112 112 "IPython %s -- An enhanced Interactive Python."
113 113 % (__version__,),
114 114 """\
115 ? -> Introduction to IPython's features
115 ? -> Introduction and overview of IPython's features.
116 116 %quickref -> Quick reference.
117 117 help -> Python's own help system.
118 118 object? -> Details about 'object'. ?object also works, ?? prints more.
119 119 """ ]
120 120
121 121 IP.usage = interactive_usage
122 122
123 123 # Platform-dependent suffix and directory names. We use _ipython instead
124 124 # of .ipython under win32 b/c there's software that breaks with .named
125 125 # directories on that platform.
126 126 if os.name == 'posix':
127 127 rc_suffix = ''
128 128 ipdir_def = '.ipython'
129 129 else:
130 130 rc_suffix = '.ini'
131 131 ipdir_def = '_ipython'
132 132
133 133 # default directory for configuration
134 134 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
135 135 os.path.join(IP.home_dir,ipdir_def)))
136 136
137 137 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
138 138
139 139 # we need the directory where IPython itself is installed
140 140 import IPython
141 141 IPython_dir = os.path.dirname(IPython.__file__)
142 142 del IPython
143 143
144 144 #-------------------------------------------------------------------------
145 145 # Command line handling
146 146
147 147 # Valid command line options (uses DPyGetOpt syntax, like Perl's
148 148 # GetOpt::Long)
149 149
150 150 # Any key not listed here gets deleted even if in the file (like session
151 151 # or profile). That's deliberate, to maintain the rc namespace clean.
152 152
153 153 # Each set of options appears twice: under _conv only the names are
154 154 # listed, indicating which type they must be converted to when reading the
155 155 # ipythonrc file. And under DPyGetOpt they are listed with the regular
156 156 # DPyGetOpt syntax (=s,=i,:f,etc).
157 157
158 158 # Make sure there's a space before each end of line (they get auto-joined!)
159 159 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
160 160 'c=s classic|cl color_info! colors=s confirm_exit! '
161 161 'debug! deep_reload! editor=s log|l messages! nosep '
162 162 'object_info_string_level=i pdb! '
163 163 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
164 164 'pylab_import_all! '
165 165 'quick screen_length|sl=i prompts_pad_left=i '
166 166 'logfile|lf=s logplay|lp=s profile|p=s '
167 167 'readline! readline_merge_completions! '
168 168 'readline_omit__names! '
169 169 'rcfile=s separate_in|si=s separate_out|so=s '
170 170 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
171 171 'magic_docstrings system_verbose! '
172 172 'multi_line_specials! '
173 173 'term_title! wxversion=s '
174 174 'autoedit_syntax!')
175 175
176 176 # Options that can *only* appear at the cmd line (not in rcfiles).
177 177
178 178 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
179 179 # the 'C-c !' command in emacs automatically appends a -i option at the end.
180 180 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
181 181 'gthread! qthread! q4thread! wthread! pylab! tk!')
182 182
183 183 # Build the actual name list to be used by DPyGetOpt
184 184 opts_names = qw(cmdline_opts) + qw(cmdline_only)
185 185
186 186 # Set sensible command line defaults.
187 187 # This should have everything from cmdline_opts and cmdline_only
188 188 opts_def = Struct(autocall = 1,
189 189 autoedit_syntax = 0,
190 190 autoindent = 0,
191 191 automagic = 1,
192 192 banner = 1,
193 193 cache_size = 1000,
194 194 c = '',
195 195 classic = 0,
196 196 colors = 'NoColor',
197 197 color_info = 0,
198 198 confirm_exit = 1,
199 199 debug = 0,
200 200 deep_reload = 0,
201 201 editor = '0',
202 202 help = 0,
203 203 interact = 0,
204 204 ipythondir = ipythondir_def,
205 205 log = 0,
206 206 logfile = '',
207 207 logplay = '',
208 208 multi_line_specials = 1,
209 209 messages = 1,
210 210 object_info_string_level = 0,
211 211 nosep = 0,
212 212 pdb = 0,
213 213 pprint = 0,
214 214 profile = '',
215 215 prompt_in1 = 'In [\\#]: ',
216 216 prompt_in2 = ' .\\D.: ',
217 217 prompt_out = 'Out[\\#]: ',
218 218 prompts_pad_left = 1,
219 219 pylab_import_all = 1,
220 220 quiet = 0,
221 221 quick = 0,
222 222 readline = 1,
223 223 readline_merge_completions = 1,
224 224 readline_omit__names = 0,
225 225 rcfile = 'ipythonrc' + rc_suffix,
226 226 screen_length = 0,
227 227 separate_in = '\n',
228 228 separate_out = '\n',
229 229 separate_out2 = '',
230 230 system_header = 'IPython system call: ',
231 231 system_verbose = 0,
232 232 gthread = 0,
233 233 qthread = 0,
234 234 q4thread = 0,
235 235 wthread = 0,
236 236 pylab = 0,
237 237 term_title = 1,
238 238 tk = 0,
239 239 upgrade = 0,
240 240 Version = 0,
241 241 xmode = 'Verbose',
242 242 wildcards_case_sensitive = 1,
243 243 wxversion = '0',
244 244 magic_docstrings = 0, # undocumented, for doc generation
245 245 )
246 246
247 247 # Things that will *only* appear in rcfiles (not at the command line).
248 248 # Make sure there's a space before each end of line (they get auto-joined!)
249 249 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
250 250 qw_lol: 'import_some ',
251 251 # for things with embedded whitespace:
252 252 list_strings:'execute alias readline_parse_and_bind ',
253 253 # Regular strings need no conversion:
254 254 None:'readline_remove_delims ',
255 255 }
256 256 # Default values for these
257 257 rc_def = Struct(include = [],
258 258 import_mod = [],
259 259 import_all = [],
260 260 import_some = [[]],
261 261 execute = [],
262 262 execfile = [],
263 263 alias = [],
264 264 readline_parse_and_bind = [],
265 265 readline_remove_delims = '',
266 266 )
267 267
268 268 # Build the type conversion dictionary from the above tables:
269 269 typeconv = rcfile_opts.copy()
270 270 typeconv.update(optstr2types(cmdline_opts))
271 271
272 272 # FIXME: the None key appears in both, put that back together by hand. Ugly!
273 273 typeconv[None] += ' ' + rcfile_opts[None]
274 274
275 275 # Remove quotes at ends of all strings (used to protect spaces)
276 276 typeconv[unquote_ends] = typeconv[None]
277 277 del typeconv[None]
278 278
279 279 # Build the list we'll use to make all config decisions with defaults:
280 280 opts_all = opts_def.copy()
281 281 opts_all.update(rc_def)
282 282
283 283 # Build conflict resolver for recursive loading of config files:
284 284 # - preserve means the outermost file maintains the value, it is not
285 285 # overwritten if an included file has the same key.
286 286 # - add_flip applies + to the two values, so it better make sense to add
287 287 # those types of keys. But it flips them first so that things loaded
288 288 # deeper in the inclusion chain have lower precedence.
289 289 conflict = {'preserve': ' '.join([ typeconv[int],
290 290 typeconv[unquote_ends] ]),
291 291 'add_flip': ' '.join([ typeconv[qwflat],
292 292 typeconv[qw_lol],
293 293 typeconv[list_strings] ])
294 294 }
295 295
296 296 # Now actually process the command line
297 297 getopt = DPyGetOpt.DPyGetOpt()
298 298 getopt.setIgnoreCase(0)
299 299
300 300 getopt.parseConfiguration(opts_names)
301 301
302 302 try:
303 303 getopt.processArguments(argv)
304 304 except:
305 305 print cmd_line_usage
306 306 warn('\nError in Arguments: ' + `sys.exc_value`)
307 307 sys.exit(1)
308 308
309 309 # convert the options dict to a struct for much lighter syntax later
310 310 opts = Struct(getopt.optionValues)
311 311 args = getopt.freeValues
312 312
313 313 # this is the struct (which has default values at this point) with which
314 314 # we make all decisions:
315 315 opts_all.update(opts)
316 316
317 317 # Options that force an immediate exit
318 318 if opts_all.help:
319 319 page(cmd_line_usage)
320 320 sys.exit()
321 321
322 322 if opts_all.Version:
323 323 print __version__
324 324 sys.exit()
325 325
326 326 if opts_all.magic_docstrings:
327 327 IP.magic_magic('-latex')
328 328 sys.exit()
329 329
330 330 # add personal ipythondir to sys.path so that users can put things in
331 331 # there for customization
332 332 sys.path.append(os.path.abspath(opts_all.ipythondir))
333 333
334 334 # Create user config directory if it doesn't exist. This must be done
335 335 # *after* getting the cmd line options.
336 336 if not os.path.isdir(opts_all.ipythondir):
337 337 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
338 338
339 339 # upgrade user config files while preserving a copy of the originals
340 340 if opts_all.upgrade:
341 341 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
342 342
343 343 # check mutually exclusive options in the *original* command line
344 344 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
345 345 qw('classic profile'),qw('classic rcfile')])
346 346
347 347 #---------------------------------------------------------------------------
348 348 # Log replay
349 349
350 350 # if -logplay, we need to 'become' the other session. That basically means
351 351 # replacing the current command line environment with that of the old
352 352 # session and moving on.
353 353
354 354 # this is needed so that later we know we're in session reload mode, as
355 355 # opts_all will get overwritten:
356 356 load_logplay = 0
357 357
358 358 if opts_all.logplay:
359 359 load_logplay = opts_all.logplay
360 360 opts_debug_save = opts_all.debug
361 361 try:
362 362 logplay = open(opts_all.logplay)
363 363 except IOError:
364 364 if opts_all.debug: IP.InteractiveTB()
365 365 warn('Could not open logplay file '+`opts_all.logplay`)
366 366 # restore state as if nothing had happened and move on, but make
367 367 # sure that later we don't try to actually load the session file
368 368 logplay = None
369 369 load_logplay = 0
370 370 del opts_all.logplay
371 371 else:
372 372 try:
373 373 logplay.readline()
374 374 logplay.readline();
375 375 # this reloads that session's command line
376 376 cmd = logplay.readline()[6:]
377 377 exec cmd
378 378 # restore the true debug flag given so that the process of
379 379 # session loading itself can be monitored.
380 380 opts.debug = opts_debug_save
381 381 # save the logplay flag so later we don't overwrite the log
382 382 opts.logplay = load_logplay
383 383 # now we must update our own structure with defaults
384 384 opts_all.update(opts)
385 385 # now load args
386 386 cmd = logplay.readline()[6:]
387 387 exec cmd
388 388 logplay.close()
389 389 except:
390 390 logplay.close()
391 391 if opts_all.debug: IP.InteractiveTB()
392 392 warn("Logplay file lacking full configuration information.\n"
393 393 "I'll try to read it, but some things may not work.")
394 394
395 395 #-------------------------------------------------------------------------
396 396 # set up output traps: catch all output from files, being run, modules
397 397 # loaded, etc. Then give it to the user in a clean form at the end.
398 398
399 399 msg_out = 'Output messages. '
400 400 msg_err = 'Error messages. '
401 401 msg_sep = '\n'
402 402 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
403 403 msg_err,msg_sep,debug,
404 404 quiet_out=1),
405 405 user_exec = OutputTrap('User File Execution',msg_out,
406 406 msg_err,msg_sep,debug),
407 407 logplay = OutputTrap('Log Loader',msg_out,
408 408 msg_err,msg_sep,debug),
409 409 summary = ''
410 410 )
411 411
412 412 #-------------------------------------------------------------------------
413 413 # Process user ipythonrc-type configuration files
414 414
415 415 # turn on output trapping and log to msg.config
416 416 # remember that with debug on, trapping is actually disabled
417 417 msg.config.trap_all()
418 418
419 419 # look for rcfile in current or default directory
420 420 try:
421 421 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
422 422 except IOError:
423 423 if opts_all.debug: IP.InteractiveTB()
424 424 warn('Configuration file %s not found. Ignoring request.'
425 425 % (opts_all.rcfile) )
426 426
427 427 # 'profiles' are a shorthand notation for config filenames
428 428 profile_handled_by_legacy = False
429 429 if opts_all.profile:
430 430
431 431 try:
432 432 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
433 433 + rc_suffix,
434 434 opts_all.ipythondir)
435 435 profile_handled_by_legacy = True
436 436 except IOError:
437 437 if opts_all.debug: IP.InteractiveTB()
438 438 opts.profile = '' # remove profile from options if invalid
439 439 # We won't warn anymore, primary method is ipy_profile_PROFNAME
440 440 # which does trigger a warning.
441 441
442 442 # load the config file
443 443 rcfiledata = None
444 444 if opts_all.quick:
445 445 print 'Launching IPython in quick mode. No config file read.'
446 446 elif opts_all.rcfile:
447 447 try:
448 448 cfg_loader = ConfigLoader(conflict)
449 449 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
450 450 'include',opts_all.ipythondir,
451 451 purge = 1,
452 452 unique = conflict['preserve'])
453 453 except:
454 454 IP.InteractiveTB()
455 455 warn('Problems loading configuration file '+
456 456 `opts_all.rcfile`+
457 457 '\nStarting with default -bare bones- configuration.')
458 458 else:
459 459 warn('No valid configuration file found in either currrent directory\n'+
460 460 'or in the IPython config. directory: '+`opts_all.ipythondir`+
461 461 '\nProceeding with internal defaults.')
462 462
463 463 #------------------------------------------------------------------------
464 464 # Set exception handlers in mode requested by user.
465 465 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
466 466 IP.magic_xmode(opts_all.xmode)
467 467 otrap.release_out()
468 468
469 469 #------------------------------------------------------------------------
470 470 # Execute user config
471 471
472 472 # Create a valid config structure with the right precedence order:
473 473 # defaults < rcfile < command line. This needs to be in the instance, so
474 474 # that method calls below that rely on it find it.
475 475 IP.rc = rc_def.copy()
476 476
477 477 # Work with a local alias inside this routine to avoid unnecessary
478 478 # attribute lookups.
479 479 IP_rc = IP.rc
480 480
481 481 IP_rc.update(opts_def)
482 482 if rcfiledata:
483 483 # now we can update
484 484 IP_rc.update(rcfiledata)
485 485 IP_rc.update(opts)
486 486 IP_rc.update(rc_override)
487 487
488 488 # Store the original cmd line for reference:
489 489 IP_rc.opts = opts
490 490 IP_rc.args = args
491 491
492 492 # create a *runtime* Struct like rc for holding parameters which may be
493 493 # created and/or modified by runtime user extensions.
494 494 IP.runtime_rc = Struct()
495 495
496 496 # from this point on, all config should be handled through IP_rc,
497 497 # opts* shouldn't be used anymore.
498 498
499 499
500 500 # update IP_rc with some special things that need manual
501 501 # tweaks. Basically options which affect other options. I guess this
502 502 # should just be written so that options are fully orthogonal and we
503 503 # wouldn't worry about this stuff!
504 504
505 505 if IP_rc.classic:
506 506 IP_rc.quick = 1
507 507 IP_rc.cache_size = 0
508 508 IP_rc.pprint = 0
509 509 IP_rc.prompt_in1 = '>>> '
510 510 IP_rc.prompt_in2 = '... '
511 511 IP_rc.prompt_out = ''
512 512 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
513 513 IP_rc.colors = 'NoColor'
514 514 IP_rc.xmode = 'Plain'
515 515
516 516 IP.pre_config_initialization()
517 517 # configure readline
518 518 # Define the history file for saving commands in between sessions
519 519 if IP_rc.profile:
520 520 histfname = 'history-%s' % IP_rc.profile
521 521 else:
522 522 histfname = 'history'
523 523 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
524 524
525 525 # update exception handlers with rc file status
526 526 otrap.trap_out() # I don't want these messages ever.
527 527 IP.magic_xmode(IP_rc.xmode)
528 528 otrap.release_out()
529 529
530 530 # activate logging if requested and not reloading a log
531 531 if IP_rc.logplay:
532 532 IP.magic_logstart(IP_rc.logplay + ' append')
533 533 elif IP_rc.logfile:
534 534 IP.magic_logstart(IP_rc.logfile)
535 535 elif IP_rc.log:
536 536 IP.magic_logstart()
537 537
538 538 # find user editor so that it we don't have to look it up constantly
539 539 if IP_rc.editor.strip()=='0':
540 540 try:
541 541 ed = os.environ['EDITOR']
542 542 except KeyError:
543 543 if os.name == 'posix':
544 544 ed = 'vi' # the only one guaranteed to be there!
545 545 else:
546 546 ed = 'notepad' # same in Windows!
547 547 IP_rc.editor = ed
548 548
549 549 # Keep track of whether this is an embedded instance or not (useful for
550 550 # post-mortems).
551 551 IP_rc.embedded = IP.embedded
552 552
553 553 # Recursive reload
554 554 try:
555 555 from IPython import deep_reload
556 556 if IP_rc.deep_reload:
557 557 __builtin__.reload = deep_reload.reload
558 558 else:
559 559 __builtin__.dreload = deep_reload.reload
560 560 del deep_reload
561 561 except ImportError:
562 562 pass
563 563
564 564 # Save the current state of our namespace so that the interactive shell
565 565 # can later know which variables have been created by us from config files
566 566 # and loading. This way, loading a file (in any way) is treated just like
567 567 # defining things on the command line, and %who works as expected.
568 568
569 569 # DON'T do anything that affects the namespace beyond this point!
570 570 IP.internal_ns.update(__main__.__dict__)
571 571
572 572 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
573 573
574 574 # Now run through the different sections of the users's config
575 575 if IP_rc.debug:
576 576 print 'Trying to execute the following configuration structure:'
577 577 print '(Things listed first are deeper in the inclusion tree and get'
578 578 print 'loaded first).\n'
579 579 pprint(IP_rc.__dict__)
580 580
581 581 for mod in IP_rc.import_mod:
582 582 try:
583 583 exec 'import '+mod in IP.user_ns
584 584 except :
585 585 IP.InteractiveTB()
586 586 import_fail_info(mod)
587 587
588 588 for mod_fn in IP_rc.import_some:
589 589 if not mod_fn == []:
590 590 mod,fn = mod_fn[0],','.join(mod_fn[1:])
591 591 try:
592 592 exec 'from '+mod+' import '+fn in IP.user_ns
593 593 except :
594 594 IP.InteractiveTB()
595 595 import_fail_info(mod,fn)
596 596
597 597 for mod in IP_rc.import_all:
598 598 try:
599 599 exec 'from '+mod+' import *' in IP.user_ns
600 600 except :
601 601 IP.InteractiveTB()
602 602 import_fail_info(mod)
603 603
604 604 for code in IP_rc.execute:
605 605 try:
606 606 exec code in IP.user_ns
607 607 except:
608 608 IP.InteractiveTB()
609 609 warn('Failure executing code: ' + `code`)
610 610
611 611 # Execute the files the user wants in ipythonrc
612 612 for file in IP_rc.execfile:
613 613 try:
614 614 file = filefind(file,sys.path+[IPython_dir])
615 615 except IOError:
616 616 warn(itpl('File $file not found. Skipping it.'))
617 617 else:
618 618 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
619 619
620 620 # finally, try importing ipy_*_conf for final configuration
621 621 try:
622 622 import ipy_system_conf
623 623 except ImportError:
624 624 if opts_all.debug: IP.InteractiveTB()
625 625 warn("Could not import 'ipy_system_conf'")
626 626 except:
627 627 IP.InteractiveTB()
628 628 import_fail_info('ipy_system_conf')
629 629
630 630 # only import prof module if ipythonrc-PROF was not found
631 631 if opts_all.profile and not profile_handled_by_legacy:
632 632 profmodname = 'ipy_profile_' + opts_all.profile
633 633 try:
634 634 __import__(profmodname)
635 635 except:
636 636 IP.InteractiveTB()
637 637 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
638 638 import_fail_info(profmodname)
639 639 else:
640 640 import ipy_profile_none
641 641 try:
642 642 import ipy_user_conf
643 643
644 644 except:
645 645 conf = opts_all.ipythondir + "/ipy_user_conf.py"
646 646 IP.InteractiveTB()
647 647 if not os.path.isfile(conf):
648 648 warn(conf + ' does not exist, please run %upgrade!')
649 649
650 650 import_fail_info("ipy_user_conf")
651 651
652 652 # finally, push the argv to options again to ensure highest priority
653 653 IP_rc.update(opts)
654 654
655 655 # release stdout and stderr and save config log into a global summary
656 656 msg.config.release_all()
657 657 if IP_rc.messages:
658 658 msg.summary += msg.config.summary_all()
659 659
660 660 #------------------------------------------------------------------------
661 661 # Setup interactive session
662 662
663 663 # Now we should be fully configured. We can then execute files or load
664 664 # things only needed for interactive use. Then we'll open the shell.
665 665
666 666 # Take a snapshot of the user namespace before opening the shell. That way
667 667 # we'll be able to identify which things were interactively defined and
668 668 # which were defined through config files.
669 669 IP.user_config_ns.update(IP.user_ns)
670 670
671 671 # Force reading a file as if it were a session log. Slower but safer.
672 672 if load_logplay:
673 673 print 'Replaying log...'
674 674 try:
675 675 if IP_rc.debug:
676 676 logplay_quiet = 0
677 677 else:
678 678 logplay_quiet = 1
679 679
680 680 msg.logplay.trap_all()
681 681 IP.safe_execfile(load_logplay,IP.user_ns,
682 682 islog = 1, quiet = logplay_quiet)
683 683 msg.logplay.release_all()
684 684 if IP_rc.messages:
685 685 msg.summary += msg.logplay.summary_all()
686 686 except:
687 687 warn('Problems replaying logfile %s.' % load_logplay)
688 688 IP.InteractiveTB()
689 689
690 690 # Load remaining files in command line
691 691 msg.user_exec.trap_all()
692 692
693 693 # Do NOT execute files named in the command line as scripts to be loaded
694 694 # by embedded instances. Doing so has the potential for an infinite
695 695 # recursion if there are exceptions thrown in the process.
696 696
697 697 # XXX FIXME: the execution of user files should be moved out to after
698 698 # ipython is fully initialized, just as if they were run via %run at the
699 699 # ipython prompt. This would also give them the benefit of ipython's
700 700 # nice tracebacks.
701 701
702 702 if (not embedded and IP_rc.args and
703 703 not IP_rc.args[0].lower().endswith('.ipy')):
704 704 name_save = IP.user_ns['__name__']
705 705 IP.user_ns['__name__'] = '__main__'
706 706 # Set our own excepthook in case the user code tries to call it
707 707 # directly. This prevents triggering the IPython crash handler.
708 708 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
709 709
710 710 save_argv = sys.argv[1:] # save it for later restoring
711 711
712 712 sys.argv = args
713 713
714 714 try:
715 715 IP.safe_execfile(args[0], IP.user_ns)
716 716 finally:
717 717 # Reset our crash handler in place
718 718 sys.excepthook = old_excepthook
719 719 sys.argv[:] = save_argv
720 720 IP.user_ns['__name__'] = name_save
721 721
722 722 msg.user_exec.release_all()
723 723
724 724 if IP_rc.messages:
725 725 msg.summary += msg.user_exec.summary_all()
726 726
727 727 # since we can't specify a null string on the cmd line, 0 is the equivalent:
728 728 if IP_rc.nosep:
729 729 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
730 730 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
731 731 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
732 732 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
733 733 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
734 734 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
735 735 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
736 736
737 737 # Determine how many lines at the bottom of the screen are needed for
738 738 # showing prompts, so we can know wheter long strings are to be printed or
739 739 # paged:
740 740 num_lines_bot = IP_rc.separate_in.count('\n')+1
741 741 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
742 742
743 743 # configure startup banner
744 744 if IP_rc.c: # regular python doesn't print the banner with -c
745 745 IP_rc.banner = 0
746 746 if IP_rc.banner:
747 747 BANN_P = IP.BANNER_PARTS
748 748 else:
749 749 BANN_P = []
750 750
751 751 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
752 752
753 753 # add message log (possibly empty)
754 754 if msg.summary: BANN_P.append(msg.summary)
755 755 # Final banner is a string
756 756 IP.BANNER = '\n'.join(BANN_P)
757 757
758 758 # Finalize the IPython instance. This assumes the rc structure is fully
759 759 # in place.
760 760 IP.post_config_initialization()
761 761
762 762 return IP
763 763 #************************ end of file <ipmaker.py> **************************
@@ -1,652 +1,654 b''
1 1 # -*- coding: utf-8 -*-
2 2 #*****************************************************************************
3 3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 4 #
5 5 # Distributed under the terms of the BSD License. The full license is in
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 # $Id: usage.py 2710 2007-09-04 21:10:10Z vivainio $
9 # $Id: usage.py 2723 2007-09-07 07:44:16Z fperez $
10 10
11 11 from IPython import Release
12 12 __author__ = '%s <%s>' % Release.authors['Fernando']
13 13 __license__ = Release.license
14 14 __version__ = Release.version
15 15
16 16 __doc__ = """
17 17 IPython -- An enhanced Interactive Python
18 18 =========================================
19 19
20 20 A Python shell with automatic history (input and output), dynamic object
21 21 introspection, easier configuration, command completion, access to the system
22 22 shell and more.
23 23
24 24 IPython can also be embedded in running programs. See EMBEDDING below.
25 25
26 26
27 27 USAGE
28 28 ipython [options] files
29 29
30 30 If invoked with no options, it executes all the files listed in
31 31 sequence and drops you into the interpreter while still acknowledging
32 32 any options you may have set in your ipythonrc file. This behavior is
33 33 different from standard Python, which when called as python -i will
34 34 only execute one file and will ignore your configuration setup.
35 35
36 36 Please note that some of the configuration options are not available at
37 37 the command line, simply because they are not practical here. Look into
38 38 your ipythonrc configuration file for details on those. This file
39 39 typically installed in the $HOME/.ipython directory.
40 40
41 41 For Windows users, $HOME resolves to C:\\Documents and
42 42 Settings\\YourUserName in most instances, and _ipython is used instead
43 43 of .ipython, since some Win32 programs have problems with dotted names
44 44 in directories.
45 45
46 46 In the rest of this text, we will refer to this directory as
47 47 IPYTHONDIR.
48 48
49 49
50 50 SPECIAL THREADING OPTIONS
51 51 The following special options are ONLY valid at the beginning of the
52 52 command line, and not later. This is because they control the initial-
53 53 ization of ipython itself, before the normal option-handling mechanism
54 54 is active.
55 55
56 56 -gthread, -qthread, -q4thread, -wthread, -pylab
57 57
58 58 Only ONE of these can be given, and it can only be given as the
59 59 first option passed to IPython (it will have no effect in any
60 60 other position). They provide threading support for the GTK, QT
61 61 and WXWidgets toolkits, and for the matplotlib library.
62 62
63 63 With any of the first four options, IPython starts running a
64 64 separate thread for the graphical toolkit's operation, so that
65 65 you can open and control graphical elements from within an
66 66 IPython command line, without blocking. All four provide
67 67 essentially the same functionality, respectively for GTK, QT3,
68 68 QT4 and WXWidgets (via their Python interfaces).
69 69
70 70 Note that with -wthread, you can additionally use the -wxversion
71 71 option to request a specific version of wx to be used. This
72 72 requires that you have the 'wxversion' Python module installed,
73 73 which is part of recent wxPython distributions.
74 74
75 75 If -pylab is given, IPython loads special support for the mat-
76 76 plotlib library (http://matplotlib.sourceforge.net), allowing
77 77 interactive usage of any of its backends as defined in the
78 78 user's .matplotlibrc file. It automatically activates GTK, QT
79 79 or WX threading for IPyhton if the choice of matplotlib backend
80 80 requires it. It also modifies the %run command to correctly
81 81 execute (without blocking) any matplotlib-based script which
82 82 calls show() at the end.
83 83
84 84 -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is
85 85 configured to use GTK, QT or WX), will normally block Tk
86 86 graphical interfaces. This means that when GTK, QT or WX
87 87 threading is active, any attempt to open a Tk GUI will result in
88 88 a dead window, and possibly cause the Python interpreter to
89 89 crash. An extra option, -tk, is available to address this
90 90 issue. It can ONLY be given as a SECOND option after any of the
91 91 above (-gthread, -qthread, q4thread, -wthread or -pylab).
92 92
93 93 If -tk is given, IPython will try to coordinate Tk threading
94 94 with GTK, QT or WX. This is however potentially unreliable, and
95 95 you will have to test on your platform and Python configuration
96 96 to determine whether it works for you. Debian users have
97 97 reported success, apparently due to the fact that Debian builds
98 98 all of Tcl, Tk, Tkinter and Python with pthreads support. Under
99 99 other Linux environments (such as Fedora Core 2/3), this option
100 100 has caused random crashes and lockups of the Python interpreter.
101 101 Under other operating systems (Mac OSX and Windows), you'll need
102 102 to try it to find out, since currently no user reports are
103 103 available.
104 104
105 105 There is unfortunately no way for IPython to determine at run-
106 106 time whether -tk will work reliably or not, so you will need to
107 107 do some experiments before relying on it for regular work.
108 108
109 109 A WARNING ABOUT SIGNALS AND THREADS
110 110
111 111 When any of the thread systems (GTK, QT or WX) are active, either
112 112 directly or via -pylab with a threaded backend, it is impossible to
113 113 interrupt long-running Python code via Ctrl-C. IPython can not pass
114 114 the KeyboardInterrupt exception (or the underlying SIGINT) across
115 115 threads, so any long-running process started from IPython will run to
116 116 completion, or will have to be killed via an external (OS-based)
117 117 mechanism.
118 118
119 119 To the best of my knowledge, this limitation is imposed by the Python
120 120 interpreter itself, and it comes from the difficulty of writing
121 121 portable signal/threaded code. If any user is an expert on this topic
122 122 and can suggest a better solution, I would love to hear about it. In
123 123 the IPython sources, look at the Shell.py module, and in particular at
124 124 the runcode() method.
125 125
126 126 REGULAR OPTIONS
127 127 After the above threading options have been given, regular options can
128 128 follow in any order. All options can be abbreviated to their shortest
129 129 non-ambiguous form and are case-sensitive. One or two dashes can be
130 130 used. Some options have an alternate short form, indicated after a |.
131 131
132 132 Most options can also be set from your ipythonrc configuration file.
133 133 See the provided examples for assistance. Options given on the comman-
134 134 dline override the values set in the ipythonrc file.
135 135
136 136 All options with a [no] prepended can be specified in negated form
137 137 (using -nooption instead of -option) to turn the feature off.
138 138
139 139 -h, --help
140 140 Show summary of options.
141 141
142 142 -pylab This can only be given as the first option passed to IPython (it
143 143 will have no effect in any other position). It adds special sup-
144 144 port for the matplotlib library (http://matplotlib.source-
145 145 forge.net), allowing interactive usage of any of its backends as
146 146 defined in the user's .matplotlibrc file. It automatically
147 147 activates GTK or WX threading for IPyhton if the choice of mat-
148 148 plotlib backend requires it. It also modifies the @run command
149 149 to correctly execute (without blocking) any matplotlib-based
150 150 script which calls show() at the end.
151 151
152 152 -autocall <val>
153 153 Make IPython automatically call any callable object even if you
154 154 didn't type explicit parentheses. For example, 'str 43' becomes
155 155 'str(43)' automatically. The value can be '0' to disable the
156 156 feature, '1' for 'smart' autocall, where it is not applied if
157 157 there are no more arguments on the line, and '2' for 'full'
158 158 autocall, where all callable objects are automatically called
159 159 (even if no arguments are present). The default is '1'.
160 160
161 161 -[no]autoindent
162 162 Turn automatic indentation on/off.
163 163
164 164 -[no]automagic
165 165 Make magic commands automatic (without needing their first char-
166 166 acter to be %). Type %magic at the IPython prompt for more
167 167 information.
168 168
169 169 -[no]autoedit_syntax
170 170 When a syntax error occurs after editing a file, automatically
171 171 open the file to the trouble causing line for convenient fixing.
172 172
173 173 -[no]banner
174 174 Print the intial information banner (default on).
175 175
176 176 -c <command>
177 177 Execute the given command string, and set sys.argv to ['c'].
178 178 This is similar to the -c option in the normal Python inter-
179 179 preter.
180 180
181 181 -cache_size|cs <n>
182 182 Size of the output cache (maximum number of entries to hold in
183 183 memory). The default is 1000, you can change it permanently in
184 184 your config file. Setting it to 0 completely disables the
185 185 caching system, and the minimum value accepted is 20 (if you
186 186 provide a value less than 20, it is reset to 0 and a warning is
187 187 issued). This limit is defined because otherwise you'll spend
188 188 more time re-flushing a too small cache than working.
189 189
190 190 -classic|cl
191 191 Gives IPython a similar feel to the classic Python prompt.
192 192
193 193 -colors <scheme>
194 194 Color scheme for prompts and exception reporting. Currently
195 195 implemented: NoColor, Linux, and LightBG.
196 196
197 197 -[no]color_info
198 198 IPython can display information about objects via a set of func-
199 199 tions, and optionally can use colors for this, syntax highlight-
200 200 ing source code and various other elements. However, because
201 201 this information is passed through a pager (like 'less') and
202 202 many pagers get confused with color codes, this option is off by
203 203 default. You can test it and turn it on permanently in your
204 204 ipythonrc file if it works for you. As a reference, the 'less'
205 205 pager supplied with Mandrake 8.2 works ok, but that in RedHat
206 206 7.2 doesn't.
207 207
208 208 Test it and turn it on permanently if it works with your system.
209 209 The magic function @color_info allows you to toggle this inter-
210 210 actively for testing.
211 211
212 212 -[no]confirm_exit
213 213 Set to confirm when you try to exit IPython with an EOF (Con-
214 214 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
215 215 magic functions @Exit or @Quit you can force a direct exit,
216 216 bypassing any confirmation.
217 217
218 218 -[no]debug
219 219 Show information about the loading process. Very useful to pin
220 220 down problems with your configuration files or to get details
221 221 about session restores.
222 222
223 223 -[no]deep_reload
224 224 IPython can use the deep_reload module which reloads changes in
225 225 modules recursively (it replaces the reload() function, so you
226 226 don't need to change anything to use it). deep_reload() forces a
227 227 full reload of modules whose code may have changed, which the
228 228 default reload() function does not.
229 229
230 230 When deep_reload is off, IPython will use the normal reload(),
231 231 but deep_reload will still be available as dreload(). This fea-
232 232 ture is off by default [which means that you have both normal
233 233 reload() and dreload()].
234 234
235 235 -editor <name>
236 236 Which editor to use with the @edit command. By default, IPython
237 237 will honor your EDITOR environment variable (if not set, vi is
238 238 the Unix default and notepad the Windows one). Since this editor
239 239 is invoked on the fly by IPython and is meant for editing small
240 240 code snippets, you may want to use a small, lightweight editor
241 241 here (in case your default EDITOR is something like Emacs).
242 242
243 243 -ipythondir <name>
244 244 The name of your IPython configuration directory IPYTHONDIR.
245 245 This can also be specified through the environment variable
246 246 IPYTHONDIR.
247 247
248 248 -log|l Generate a log file of all input. The file is named
249 249 ipython_log.py in your current directory (which prevents logs
250 250 from multiple IPython sessions from trampling each other). You
251 251 can use this to later restore a session by loading your logfile
252 252 as a file to be executed with option -logplay (see below).
253 253
254 254 -logfile|lf
255 255 Specify the name of your logfile.
256 256
257 257 -logplay|lp
258 258 Replay a previous log. For restoring a session as close as pos-
259 259 sible to the state you left it in, use this option (don't just
260 260 run the logfile). With -logplay, IPython will try to reconstruct
261 261 the previous working environment in full, not just execute the
262 262 commands in the logfile.
263 263 When a session is restored, logging is automatically turned on
264 264 again with the name of the logfile it was invoked with (it is
265 265 read from the log header). So once you've turned logging on for
266 266 a session, you can quit IPython and reload it as many times as
267 267 you want and it will continue to log its history and restore
268 268 from the beginning every time.
269 269
270 270 Caveats: there are limitations in this option. The history vari-
271 271 ables _i*,_* and _dh don't get restored properly. In the future
272 272 we will try to implement full session saving by writing and
273 273 retrieving a failed because of inherent limitations of Python's
274 274 Pickle module, so this may have to wait.
275 275
276 276 -[no]messages
277 277 Print messages which IPython collects about its startup process
278 278 (default on).
279 279
280 280 -[no]pdb
281 281 Automatically call the pdb debugger after every uncaught excep-
282 282 tion. If you are used to debugging using pdb, this puts you
283 283 automatically inside of it after any call (either in IPython or
284 284 in code called by it) which triggers an exception which goes
285 285 uncaught.
286 286
287 287 -[no]pprint
288 288 IPython can optionally use the pprint (pretty printer) module
289 289 for displaying results. pprint tends to give a nicer display of
290 290 nested data structures. If you like it, you can turn it on per-
291 291 manently in your config file (default off).
292 292
293 293 -profile|p <name>
294 294 Assume that your config file is ipythonrc-<name> (looks in cur-
295 295 rent dir first, then in IPYTHONDIR). This is a quick way to keep
296 296 and load multiple config files for different tasks, especially
297 297 if you use the include option of config files. You can keep a
298 298 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
299 299 which include this one and load extra things for particular
300 300 tasks. For example:
301 301
302 302 1) $HOME/.ipython/ipythonrc : load basic things you always want.
303 303 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
304 304 related modules.
305 305 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
306 306 plotting modules.
307 307
308 308 Since it is possible to create an endless loop by having circu-
309 309 lar file inclusions, IPython will stop if it reaches 15 recur-
310 310 sive inclusions.
311 311
312 312 -prompt_in1|pi1 <string>
313 313 Specify the string used for input prompts. Note that if you are
314 314 using numbered prompts, the number is represented with a '\#' in
315 315 the string. Don't forget to quote strings with spaces embedded
316 316 in them. Default: 'In [\#]: '.
317 317
318 318 Most bash-like escapes can be used to customize IPython's
319 319 prompts, as well as a few additional ones which are IPython-spe-
320 320 cific. All valid prompt escapes are described in detail in the
321 321 Customization section of the IPython HTML/PDF manual.
322 322
323 323 -prompt_in2|pi2 <string>
324 324 Similar to the previous option, but used for the continuation
325 325 prompts. The special sequence '\D' is similar to '\#', but with
326 326 all digits replaced dots (so you can have your continuation
327 327 prompt aligned with your input prompt). Default: ' .\D.: '
328 328 (note three spaces at the start for alignment with 'In [\#]').
329 329
330 330 -prompt_out|po <string>
331 331 String used for output prompts, also uses numbers like
332 332 prompt_in1. Default: 'Out[\#]:'.
333 333
334 334 -quick Start in bare bones mode (no config file loaded).
335 335
336 336 -rcfile <name>
337 337 Name of your IPython resource configuration file. normally
338 338 IPython loads ipythonrc (from current directory) or
339 339 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
340 340 IPython starts with a bare bones configuration (no modules
341 341 loaded at all).
342 342
343 343 -[no]readline
344 344 Use the readline library, which is needed to support name com-
345 345 pletion and command history, among other things. It is enabled
346 346 by default, but may cause problems for users of X/Emacs in
347 347 Python comint or shell buffers.
348 348
349 349 Note that emacs 'eterm' buffers (opened with M-x term) support
350 350 IPython's readline and syntax coloring fine, only 'emacs' (M-x
351 351 shell and C-c !) buffers do not.
352 352
353 353 -screen_length|sl <n>
354 354 Number of lines of your screen. This is used to control print-
355 355 ing of very long strings. Strings longer than this number of
356 356 lines will be sent through a pager instead of directly printed.
357 357
358 358 The default value for this is 0, which means IPython will auto-
359 359 detect your screen size every time it needs to print certain
360 360 potentially long strings (this doesn't change the behavior of
361 361 the 'print' keyword, it's only triggered internally). If for
362 362 some reason this isn't working well (it needs curses support),
363 363 specify it yourself. Otherwise don't change the default.
364 364
365 365 -separate_in|si <string>
366 366 Separator before input prompts. Default '0.
367 367
368 368 -separate_out|so <string>
369 369 Separator before output prompts. Default: 0 (nothing).
370 370
371 371 -separate_out2|so2 <string>
372 372 Separator after output prompts. Default: 0 (nothing).
373 373
374 374 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
375 375 Simply removes all input/output separators.
376 376
377 377 -upgrade
378 378 Allows you to upgrade your IPYTHONDIR configuration when you
379 379 install a new version of IPython. Since new versions may
380 380 include new command lines options or example files, this copies
381 381 updated ipythonrc-type files. However, it backs up (with a .old
382 382 extension) all files which it overwrites so that you can merge
383 383 back any custimizations you might have in your personal files.
384 384
385 385 -Version
386 386 Print version information and exit.
387 387
388 388 -wxversion <string>
389 389 Select a specific version of wxPython (used in conjunction with
390 390 -wthread). Requires the wxversion module, part of recent
391 391 wxPython distributions.
392 392
393 393 -xmode <modename>
394 394 Mode for exception reporting. The valid modes are Plain, Con-
395 395 text, and Verbose.
396 396
397 397 - Plain: similar to python's normal traceback printing.
398 398
399 399 - Context: prints 5 lines of context source code around each
400 400 line in the traceback.
401 401
402 402 - Verbose: similar to Context, but additionally prints the vari-
403 403 ables currently visible where the exception happened (shortening
404 404 their strings if too long). This can potentially be very slow,
405 405 if you happen to have a huge data structure whose string repre-
406 406 sentation is complex to compute. Your computer may appear to
407 407 freeze for a while with cpu usage at 100%. If this occurs, you
408 408 can cancel the traceback with Ctrl-C (maybe hitting it more than
409 409 once).
410 410
411 411
412 412 EMBEDDING
413 413 It is possible to start an IPython instance inside your own Python pro-
414 414 grams. In the documentation example files there are some illustrations
415 415 on how to do this.
416 416
417 417 This feature allows you to evalutate dynamically the state of your
418 418 code, operate with your variables, analyze them, etc. Note however
419 419 that any changes you make to values while in the shell do NOT propagate
420 420 back to the running code, so it is safe to modify your values because
421 421 you won't break your code in bizarre ways by doing so.
422 422 """
423 423
424 424 cmd_line_usage = __doc__
425 425
426 426 #---------------------------------------------------------------------------
427 427 interactive_usage = """
428 428 IPython -- An enhanced Interactive Python
429 429 =========================================
430 430
431 431 IPython offers a combination of convenient shell features, special commands
432 432 and a history mechanism for both input (command history) and output (results
433 433 caching, similar to Mathematica). It is intended to be a fully compatible
434 434 replacement for the standard Python interpreter, while offering vastly
435 435 improved functionality and flexibility.
436 436
437 437 At your system command line, type 'ipython -help' to see the command line
438 438 options available. This document only describes interactive features.
439 439
440 440 Warning: IPython relies on the existence of a global variable called __IP which
441 441 controls the shell itself. If you redefine __IP to anything, bizarre behavior
442 442 will quickly occur.
443 443
444 444 MAIN FEATURES
445 445
446 446 * Access to the standard Python help. As of Python 2.1, a help system is
447 447 available with access to object docstrings and the Python manuals. Simply
448 448 type 'help' (no quotes) to access it.
449 449
450 450 * Magic commands: type %magic for information on the magic subsystem.
451 451
452 452 * System command aliases, via the %alias command or the ipythonrc config file.
453 453
454 454 * Dynamic object information:
455 455
456 456 Typing ?word or word? prints detailed information about an object. If
457 457 certain strings in the object are too long (docstrings, code, etc.) they get
458 458 snipped in the center for brevity.
459 459
460 460 Typing ??word or word?? gives access to the full information without
461 461 snipping long strings. Long strings are sent to the screen through the less
462 462 pager if longer than the screen, printed otherwise.
463 463
464 464 The ?/?? system gives access to the full source code for any object (if
465 465 available), shows function prototypes and other useful information.
466 466
467 467 If you just want to see an object's docstring, type '%pdoc object' (without
468 468 quotes, and without % if you have automagic on).
469 469
470 470 Both %pdoc and ?/?? give you access to documentation even on things which are
471 471 not explicitely defined. Try for example typing {}.get? or after import os,
472 472 type os.path.abspath??. The magic functions %pdef, %source and %file operate
473 473 similarly.
474 474
475 475 * Completion in the local namespace, by typing TAB at the prompt.
476 476
477 477 At any time, hitting tab will complete any available python commands or
478 478 variable names, and show you a list of the possible completions if there's
479 479 no unambiguous one. It will also complete filenames in the current directory.
480 480
481 481 This feature requires the readline and rlcomplete modules, so it won't work
482 482 if your Python lacks readline support (such as under Windows).
483 483
484 484 * Search previous command history in two ways (also requires readline):
485 485
486 486 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
487 487 search through only the history items that match what you've typed so
488 488 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
489 489 normal arrow keys.
490 490
491 491 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
492 492 your history for lines that match what you've typed so far, completing as
493 493 much as it can.
494 494
495 495 * Persistent command history across sessions (readline required).
496 496
497 497 * Logging of input with the ability to save and restore a working session.
498 498
499 499 * System escape with !. Typing !ls will run 'ls' in the current directory.
500 500
501 501 * The reload command does a 'deep' reload of a module: changes made to the
502 502 module since you imported will actually be available without having to exit.
503 503
504 504 * Verbose and colored exception traceback printouts. See the magic xmode and
505 505 xcolor functions for details (just type %magic).
506 506
507 507 * Input caching system:
508 508
509 509 IPython offers numbered prompts (In/Out) with input and output caching. All
510 510 input is saved and can be retrieved as variables (besides the usual arrow
511 511 key recall).
512 512
513 513 The following GLOBAL variables always exist (so don't overwrite them!):
514 514 _i: stores previous input.
515 515 _ii: next previous.
516 516 _iii: next-next previous.
517 517 _ih : a list of all input _ih[n] is the input from line n.
518 518
519 519 Additionally, global variables named _i<n> are dynamically created (<n>
520 520 being the prompt counter), such that _i<n> == _ih[<n>]
521 521
522 522 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
523 523
524 524 You can create macros which contain multiple input lines from this history,
525 525 for later re-execution, with the %macro function.
526 526
527 527 The history function %hist allows you to see any part of your input history
528 528 by printing a range of the _i variables. Note that inputs which contain
529 529 magic functions (%) appear in the history with a prepended comment. This is
530 530 because they aren't really valid Python code, so you can't exec them.
531 531
532 532 * Output caching system:
533 533
534 534 For output that is returned from actions, a system similar to the input
535 535 cache exists but using _ instead of _i. Only actions that produce a result
536 536 (NOT assignments, for example) are cached. If you are familiar with
537 537 Mathematica, IPython's _ variables behave exactly like Mathematica's %
538 538 variables.
539 539
540 540 The following GLOBAL variables always exist (so don't overwrite them!):
541 541 _ (one underscore): previous output.
542 542 __ (two underscores): next previous.
543 543 ___ (three underscores): next-next previous.
544 544
545 545 Global variables named _<n> are dynamically created (<n> being the prompt
546 546 counter), such that the result of output <n> is always available as _<n>.
547 547
548 548 Finally, a global dictionary named _oh exists with entries for all lines
549 549 which generated output.
550 550
551 551 * Directory history:
552 552
553 553 Your history of visited directories is kept in the global list _dh, and the
554 554 magic %cd command can be used to go to any entry in that list.
555 555
556 556 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
557 557
558 558 1. Auto-parentheses
559 559 Callable objects (i.e. functions, methods, etc) can be invoked like
560 560 this (notice the commas between the arguments):
561 561 >>> callable_ob arg1, arg2, arg3
562 562 and the input will be translated to this:
563 563 --> callable_ob(arg1, arg2, arg3)
564 564 You can force auto-parentheses by using '/' as the first character
565 565 of a line. For example:
566 566 >>> /globals # becomes 'globals()'
567 567 Note that the '/' MUST be the first character on the line! This
568 568 won't work:
569 569 >>> print /globals # syntax error
570 570
571 571 In most cases the automatic algorithm should work, so you should
572 572 rarely need to explicitly invoke /. One notable exception is if you
573 573 are trying to call a function with a list of tuples as arguments (the
574 574 parenthesis will confuse IPython):
575 575 In [1]: zip (1,2,3),(4,5,6) # won't work
576 576 but this will work:
577 577 In [2]: /zip (1,2,3),(4,5,6)
578 578 ------> zip ((1,2,3),(4,5,6))
579 579 Out[2]= [(1, 4), (2, 5), (3, 6)]
580 580
581 581 IPython tells you that it has altered your command line by
582 582 displaying the new command line preceded by -->. e.g.:
583 583 In [18]: callable list
584 584 -------> callable (list)
585 585
586 586 2. Auto-Quoting
587 587 You can force auto-quoting of a function's arguments by using ',' as
588 588 the first character of a line. For example:
589 589 >>> ,my_function /home/me # becomes my_function("/home/me")
590 590
591 591 If you use ';' instead, the whole argument is quoted as a single
592 592 string (while ',' splits on whitespace):
593 593 >>> ,my_function a b c # becomes my_function("a","b","c")
594 594 >>> ;my_function a b c # becomes my_function("a b c")
595 595
596 596 Note that the ',' MUST be the first character on the line! This
597 597 won't work:
598 598 >>> x = ,my_function /home/me # syntax error
599 599 """
600 600
601 601 quick_reference = r"""
602 602 IPython -- An enhanced Interactive Python - Quick Reference Card
603 603 ================================================================
604 604
605 obj?, obj??, ?obj,??obj : Get help, or more help for object
606 ?os.p* : List names in os starting with p
605 obj?, obj?? : Get help, or more help for object (also works as
606 ?obj, ??obj).
607 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
608 %magic : Information about IPython's 'magic' % functions.
607 609
608 610 Magic functions are prefixed by %, and typically take their arguments without
609 611 parentheses, quotes or even commas for convenience.
610 612
611 613 Example magic function calls:
612 614
613 615 %alias d ls -F : 'd' is now an alias for 'ls -F'
614 616 alias d ls -F : Works if 'alias' not a python name
615 617 alist = %alias : Get list of aliases to 'alist'
616 618 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
617 619 %cd?? : See help AND source for magic %cd
618 620
619 621 System commands:
620 622
621 623 !cp a.txt b/ : System command escape, calls os.system()
622 624 cp a.txt b/ : after %rehashx, most system commands work without !
623 625 cp ${f}.txt $bar : Variable expansion in magics and system commands
624 626 files = !ls /usr : Capture sytem command output
625 627 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
626 628
627 629 History:
628 630
629 631 _i, _ii, _iii : Previous, next previous, next next previous input
630 632 _i4, _ih[2:5] : Input history line 4, lines 2-4
631 633 exec _i81 : Execute input history line #81 again
632 634 %rep 81 : Edit input history line #81
633 635 _, __, ___ : previous, next previous, next next previous output
634 636 _dh : Directory history
635 637 _oh : Output history
636 638 %hist : Command history. '%hist -g foo' search history for 'foo'
637 639
638 640 Autocall:
639 641
640 642 f 1,2 : f(1,2)
641 643 /f 1,2 : f(1,2) (forced autoparen)
642 644 ,f 1 2 : f("1","2")
643 645 ;f 1 2 : f("1 2")
644 646
645 647 Remember: TAB completion works in many contexts, not just file names
646 648 or python names.
647 649
648 650 The following magic functions are currently available:
649 651
650 652 """
651 653
652 654
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now