##// END OF EJS Templates
New wildcard support. Lightly tested, so proceed with caution. We need to...
fperez -
Show More

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

@@ -0,0 +1,157 b''
1 # -*- coding: utf-8 -*-
2 """Support for wildcard pattern matching in object inspection.
3
4 $Id: OInspect.py 608 2005-07-06 17:52:32Z fperez $
5 """
6
7 #*****************************************************************************
8 # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
9 #
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
13
14 from IPython import Release
15 __author__ = "Jörgen Stenarson <jorgen.stenarson@bostream.nu>"
16 __license__ = Release.license
17
18 import __builtin__
19 import types
20 import re
21 import pprint
22 import exceptions
23 import pdb
24 import IPython.genutils as genutils
25
26 def create_typestr2type_dicts(dont_include_in_type2type2str=["lambda"]):
27 """Return dictionaries mapping lower case typename to type objects, from
28 the types package, and vice versa."""
29 typenamelist=[]
30 for tname in dir(types):
31 if tname[-4:]=="Type":
32 typenamelist.append(tname)
33 typestr2type={}
34 type2typestr={}
35 for tname in typenamelist:
36 name=tname[:-4].lower()
37 obj=getattr(types,tname)
38 typestr2type[name]=getattr(types,tname)
39 if name in dont_include_in_type2type2str:
40 type2typestr[obj]=name
41 return typestr2type,type2typestr
42
43 typestr2type,type2typestr=create_typestr2type_dicts()
44
45 def is_type(obj,typestr_or_type):
46 """is_type(obj,typestr_or_type) verifies if obj is of a certain type or
47 group of types takes strings as parameters of the for 'tuple'<->TupleType
48 'all' matches all types. TODO: Should be extended for choosing more than
49 one type
50 """
51 if typestr_or_type=="all":
52 return True
53 if type(typestr_or_type)==types.TypeType:
54 test_type=typestr_or_type
55 else:
56 test_type=typestr2type.get(typestr_or_type,False)
57 if test_type:
58 return isinstance(obj,test_type)
59 else:
60 return False
61
62 def show_hidden(str,showhidden=False):
63 """Return true for strings starting with single _ if showhidden is true."""
64 return showhidden or str.startswith("__") or not str.startswith("_")
65
66
67 class NameSpace(object):
68 """NameSpace holds the dictionary for a namespace and implements filtering
69 on name and types"""
70 def __init__(self,obj,namepattern="*",typepattern="all",ignorecase=True,
71 showhidden=True):
72 self.showhidden=showhidden #Hide names beginning with single _
73 self.object=obj
74 self.namepattern=namepattern
75 self.typepattern=typepattern
76 self.ignorecase=ignorecase
77 if type(obj)==type(dict()):
78 self._ns=obj
79 else:
80 try:
81 self._ns=self.object.__dict__
82 except exceptions.AttributeError:
83 self._ns=dict([(key,getattr(self.object,key))
84 for key in dir(self.object)])
85
86 def get_ns(self):
87 """Return name space dictionary with objects matching type and name patterns."""
88 return self.filter(self.namepattern,self.typepattern)
89 ns=property(get_ns)
90
91 def get_ns_names(self):
92 """Return list of object names in namespace that match the patterns."""
93 return self.ns.keys()
94 ns_names=property(get_ns_names,doc="List of objects in name space that "
95 "match the type and name patterns.")
96
97 def filter(self,namepattern,typepattern):
98 """Return dictionary of filtered namespace."""
99 def glob_filter(lista,namepattern,hidehidden,ignorecase):
100 """Return list of elements in lista that match pattern."""
101 pattern=namepattern.replace("*",".*")
102 if ignorecase:
103 reg=re.compile(pattern+"$",re.I)
104 else:
105 reg=re.compile(pattern+"$")
106 result=[x for x in lista if reg.match(x) and show_hidden(x,hidehidden)]
107 return result
108 ns=self._ns
109 #Filter namespace by the namepattern
110 all=[(x,ns[x]) for x in glob_filter(ns.keys(),namepattern,
111 self.showhidden,self.ignorecase)]
112 #Filter namespace by typepattern
113 all=[(key,obj) for key,obj in all if is_type(obj,typepattern)]
114 all=dict(all)
115 return all
116
117 #TODO: Implement dictionary like access to filtered name space?
118
119 def list_namespace(namespace,typepattern,filter,ignorecase=False,showhidden=False):
120 """Return dictionary of all objects in namespace that matches typepattern
121 and filter."""
122 patternlist=filter.split(".")
123 if len(patternlist)==1:
124 ns=NameSpace(namespace,namepattern=patternlist[0],typepattern=typepattern,
125 ignorecase=ignorecase,showhidden=showhidden)
126 return ns.ns
127 if len(patternlist)>1:
128 #This is where we can change if all objects should be searched or only moduleas
129 #Just change the typepattern to module to search only modules
130 ns=NameSpace(namespace,
131 namepattern=patternlist[0],
132 typepattern="all",ignorecase=ignorecase,showhidden=showhidden)
133 res={}
134 nsdict=ns.ns
135 for name,obj in nsdict.iteritems():
136 ns=list_namespace(obj,typepattern,".".join(patternlist[1:]),
137 ignorecase=ignorecase,showhidden=showhidden)
138 for inner_name,inner_obj in ns.iteritems():
139 res["%s.%s"%(name,inner_name)]=inner_obj
140 return res
141
142 def choose_namespaces(shell,cmds):
143 """Returns a list of namespaces modified by arguments."""
144 nslist=genutils.mkdict(user=shell.user_ns,internal=shell.internal_ns,
145 builtin=__builtin__.__dict__,alias=shell.alias_table)
146 default_list=["user","builtin"] # Should this list be a user option??
147 for cmd in cmds:
148 if cmd[0]=="-": #remove from defaultlist
149 if cmd[1:] in default_list:
150 default_list.remove(cmd[1:])
151 elif cmd[0]=="+":
152 if cmd[1:] not in default_list and cmd[1:]in nslist:
153 default_list.append(cmd[1:])
154 else:
155 if cmd in nslist:
156 default_list.append(cmd[1:])
157 return [nslist[x] for x in default_list]
@@ -1,2452 +1,2509 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 908 2005-09-26 16:05:48Z fperez $"""
4 $Id: Magic.py 919 2005-10-15 07:57:05Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 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 os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time
25 25 try:
26 26 import profile,pstats
27 27 except ImportError:
28 28 profile = pstats = None
29 29 from getopt import getopt
30 30 from pprint import pprint, pformat
31 31 from cStringIO import StringIO
32 32
33 33 # Homebrewed
34 34 from IPython.Struct import Struct
35 35 from IPython.Itpl import Itpl, itpl, printpl,itplns
36 36 from IPython.FakeModule import FakeModule
37 from IPython import OInspect
38 37 from IPython.PyColorize import Parser
38 from IPython import OInspect
39 from IPython import wildcard
39 40 from IPython.genutils import *
40 41
41 42 # Globals to be set later by Magic constructor
42 43 MAGIC_PREFIX = ''
43 44 MAGIC_ESCAPE = ''
44 45
45 46 #***************************************************************************
46 47 # Utility functions
47 48 def magic2python(cmd):
48 49 """Convert a command string of magic syntax to valid Python code."""
49 50
50 51 if cmd.startswith('#'+MAGIC_ESCAPE) or \
51 52 cmd.startswith(MAGIC_ESCAPE):
52 53 if cmd[0]=='#':
53 54 cmd = cmd[1:]
54 55 # we need to return the proper line end later
55 56 if cmd[-1] == '\n':
56 57 endl = '\n'
57 58 else:
58 59 endl = ''
59 60 try:
60 61 func,args = cmd[1:].split(' ',1)
61 62 except:
62 63 func,args = cmd[1:].rstrip(),''
63 64 args = args.replace('"','\\"').replace("'","\\'").rstrip()
64 65 return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl)
65 66 else:
66 67 return cmd
67 68
68 69 def on_off(tag):
69 70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 71 return ['OFF','ON'][tag]
71 72
72 73
73 74 #****************************************************************************
74 75 # Utility classes
75 76 class Macro:
76 77 """Simple class to store the value of macros as strings.
77 78
78 79 This allows us to later exec them by checking when something is an
79 80 instance of this class."""
80 81
81 82 def __init__(self,cmds):
82 83 """Build a macro from a list of commands."""
83 84
84 85 # Since the list may include multi-line entries, first make sure that
85 86 # they've been all broken up before passing it to magic2python
86 87 cmdlist = map(magic2python,''.join(cmds).split('\n'))
87 88 self.value = '\n'.join(cmdlist)
88 89
89 90 def __str__(self):
90 91 return self.value
91 92
92 93 #***************************************************************************
93 94 # Main class implementing Magic functionality
94 95 class Magic:
95 96 """Magic functions for InteractiveShell.
96 97
97 98 Shell functions which can be reached as %function_name. All magic
98 99 functions should accept a string, which they can parse for their own
99 100 needs. This can make some functions easier to type, eg `%cd ../`
100 101 vs. `%cd("../")`
101 102
102 103 ALL definitions MUST begin with the prefix magic_. The user won't need it
103 104 at the command line, but it is is needed in the definition. """
104 105
105 106 # class globals
106 107 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
107 108 'Automagic is ON, % prefix NOT needed for magic functions.']
108 109
109 110 #......................................................................
110 111 # some utility functions
111 112
112 113 def __init__(self,shell):
113 114 # XXX This is hackish, clean up later to avoid these messy globals
114 115 global MAGIC_PREFIX, MAGIC_ESCAPE
115 116
116 117 self.options_table = {}
117 118 MAGIC_PREFIX = shell.name+'.magic_'
118 119 MAGIC_ESCAPE = shell.ESC_MAGIC
119 120 if profile is None:
120 121 self.magic_prun = self.profile_missing_notice
121 122
122 123 def profile_missing_notice(self, *args, **kwargs):
123 124 error("""\
124 125 The profile module could not be found. If you are a Debian user,
125 126 it has been removed from the standard Debian package because of its non-free
126 127 license. To use profiling, please install"python2.3-profiler" from non-free.""")
127 128
128 129 def default_option(self,fn,optstr):
129 130 """Make an entry in the options_table for fn, with value optstr"""
130 131
131 132 if fn not in self.lsmagic():
132 133 error("%s is not a magic function" % fn)
133 134 self.options_table[fn] = optstr
134 135
135 136 def lsmagic(self):
136 137 """Return a list of currently available magic functions.
137 138
138 139 Gives a list of the bare names after mangling (['ls','cd', ...], not
139 140 ['magic_ls','magic_cd',...]"""
140 141
141 142 # FIXME. This needs a cleanup, in the way the magics list is built.
142 143
143 144 # magics in class definition
144 145 class_magic = lambda fn: fn.startswith('magic_') and \
145 146 callable(Magic.__dict__[fn])
146 147 # in instance namespace (run-time user additions)
147 148 inst_magic = lambda fn: fn.startswith('magic_') and \
148 149 callable(self.__dict__[fn])
149 150 # and bound magics by user (so they can access self):
150 151 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
151 152 callable(self.__class__.__dict__[fn])
152 153 magics = filter(class_magic,Magic.__dict__.keys()) + \
153 154 filter(inst_magic,self.__dict__.keys()) + \
154 155 filter(inst_bound_magic,self.__class__.__dict__.keys())
155 156 out = []
156 157 for fn in magics:
157 158 out.append(fn.replace('magic_','',1))
158 159 out.sort()
159 160 return out
160 161
161 162 def set_shell(self,shell):
162 163 self.shell = shell
163 164 self.alias_table = shell.alias_table
164 165
165 166 def extract_input_slices(self,slices):
166 167 """Return as a string a set of input history slices.
167 168
168 169 The set of slices is given as a list of strings (like ['1','4:8','9'],
169 170 since this function is for use by magic functions which get their
170 171 arguments as strings."""
171 172
172 173 cmds = []
173 174 for chunk in slices:
174 175 if ':' in chunk:
175 176 ini,fin = map(int,chunk.split(':'))
176 177 else:
177 178 ini = int(chunk)
178 179 fin = ini+1
179 180 cmds.append(self.shell.input_hist[ini:fin])
180 181 return cmds
181 182
182 183 def _ofind(self,oname):
183 184 """Find an object in the available namespaces.
184 185
185 186 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
186 187
187 188 Has special code to detect magic functions.
188 189 """
189 190
190 191 oname = oname.strip()
191 192
192 193 # Namespaces to search in:
193 194 user_ns = self.shell.user_ns
194 195 internal_ns = self.shell.internal_ns
195 196 builtin_ns = __builtin__.__dict__
196 197 alias_ns = self.shell.alias_table
197 198
198 199 # Put them in a list. The order is important so that we find things in
199 200 # the same order that Python finds them.
200 201 namespaces = [ ('Interactive',user_ns),
201 202 ('IPython internal',internal_ns),
202 203 ('Python builtin',builtin_ns),
203 204 ('Alias',alias_ns),
204 205 ]
205 206
206 207 # initialize results to 'null'
207 208 found = 0; obj = None; ospace = None; ds = None;
208 209 ismagic = 0; isalias = 0
209 210
210 211 # Look for the given name by splitting it in parts. If the head is
211 212 # found, then we look for all the remaining parts as members, and only
212 213 # declare success if we can find them all.
213 214 oname_parts = oname.split('.')
214 215 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
215 216 for nsname,ns in namespaces:
216 217 try:
217 218 obj = ns[oname_head]
218 219 except KeyError:
219 220 continue
220 221 else:
221 222 for part in oname_rest:
222 223 try:
223 224 obj = getattr(obj,part)
224 225 except:
225 226 # Blanket except b/c some badly implemented objects
226 227 # allow __getattr__ to raise exceptions other than
227 228 # AttributeError, which then crashes IPython.
228 229 break
229 230 else:
230 231 # If we finish the for loop (no break), we got all members
231 232 found = 1
232 233 ospace = nsname
233 234 if ns == alias_ns:
234 235 isalias = 1
235 236 break # namespace loop
236 237
237 238 # Try to see if it's magic
238 239 if not found:
239 240 if oname.startswith(self.shell.ESC_MAGIC):
240 241 oname = oname[1:]
241 242 obj = getattr(self,'magic_'+oname,None)
242 243 if obj is not None:
243 244 found = 1
244 245 ospace = 'IPython internal'
245 246 ismagic = 1
246 247
247 248 # Last try: special-case some literals like '', [], {}, etc:
248 249 if not found and oname_head in ["''",'""','[]','{}','()']:
249 250 obj = eval(oname_head)
250 251 found = 1
251 252 ospace = 'Interactive'
252 253
253 254 return {'found':found, 'obj':obj, 'namespace':ospace,
254 255 'ismagic':ismagic, 'isalias':isalias}
255 256
256 257 def arg_err(self,func):
257 258 """Print docstring if incorrect arguments were passed"""
258 259 print 'Error in arguments:'
259 260 print OInspect.getdoc(func)
260 261
261 262
262 263 def format_latex(self,str):
263 264 """Format a string for latex inclusion."""
264 265
265 266 # Characters that need to be escaped for latex:
266 267 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
267 268 # Magic command names as headers:
268 269 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
269 270 re.MULTILINE)
270 271 # Magic commands
271 272 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
272 273 re.MULTILINE)
273 274 # Paragraph continue
274 275 par_re = re.compile(r'\\$',re.MULTILINE)
275 276
276 277 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
277 278 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
278 279 str = par_re.sub(r'\\\\',str)
279 280 str = escape_re.sub(r'\\\1',str)
280 281 return str
281 282
282 283 def format_screen(self,str):
283 284 """Format a string for screen printing.
284 285
285 286 This removes some latex-type format codes."""
286 287 # Paragraph continue
287 288 par_re = re.compile(r'\\$',re.MULTILINE)
288 289 str = par_re.sub('',str)
289 290 return str
290 291
291 292 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
292 293 """Parse options passed to an argument string.
293 294
294 295 The interface is similar to that of getopt(), but it returns back a
295 296 Struct with the options as keys and the stripped argument string still
296 297 as a string.
297 298
298 299 arg_str is quoted as a true sys.argv vector by calling on the fly a
299 300 python process in a subshell. This allows us to easily expand
300 301 variables, glob files, quote arguments, etc, with all the power and
301 302 correctness of the underlying system shell.
302 303
303 304 Options:
304 305 -mode: default 'string'. If given as 'list', the argument string is
305 306 returned as a list (split on whitespace) instead of a string.
306 307
307 308 -list_all: put all option values in lists. Normally only options
308 309 appearing more than once are put in a list."""
309 310
310 311 # inject default options at the beginning of the input line
311 312 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
312 313 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
313 314
314 315 mode = kw.get('mode','string')
315 316 if mode not in ['string','list']:
316 317 raise ValueError,'incorrect mode given: %s' % mode
317 318 # Get options
318 319 list_all = kw.get('list_all',0)
319 320
320 321 # Check if we have more than one argument to warrant extra processing:
321 322 odict = {} # Dictionary with options
322 323 args = arg_str.split()
323 324 if len(args) >= 1:
324 325 # If the list of inputs only has 0 or 1 thing in it, there's no
325 326 # need to look for options
326 327 argv = shlex_split(arg_str)
327 328 # Do regular option processing
328 329 opts,args = getopt(argv,opt_str,*long_opts)
329 330 for o,a in opts:
330 331 if o.startswith('--'):
331 332 o = o[2:]
332 333 else:
333 334 o = o[1:]
334 335 try:
335 336 odict[o].append(a)
336 337 except AttributeError:
337 338 odict[o] = [odict[o],a]
338 339 except KeyError:
339 340 if list_all:
340 341 odict[o] = [a]
341 342 else:
342 343 odict[o] = a
343 344
344 345 # Prepare opts,args for return
345 346 opts = Struct(odict)
346 347 if mode == 'string':
347 348 args = ' '.join(args)
348 349
349 350 return opts,args
350 351
351 352 #......................................................................
352 353 # And now the actual magic functions
353 354
354 355 # Functions for IPython shell work (vars,funcs, config, etc)
355 356 def magic_lsmagic(self, parameter_s = ''):
356 357 """List currently available magic functions."""
357 358 mesc = self.shell.ESC_MAGIC
358 359 print 'Available magic functions:\n'+mesc+\
359 360 (' '+mesc).join(self.lsmagic())
360 361 print '\n' + Magic.auto_status[self.shell.rc.automagic]
361 362 return None
362 363
363 364 def magic_magic(self, parameter_s = ''):
364 365 """Print information about the magic function system."""
365 366
366 367 mode = ''
367 368 try:
368 369 if parameter_s.split()[0] == '-latex':
369 370 mode = 'latex'
370 371 except:
371 372 pass
372 373
373 374 magic_docs = []
374 375 for fname in self.lsmagic():
375 376 mname = 'magic_' + fname
376 377 for space in (Magic,self,self.__class__):
377 378 try:
378 379 fn = space.__dict__[mname]
379 380 except KeyError:
380 381 pass
381 382 else:
382 383 break
383 384 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
384 385 fname,fn.__doc__))
385 386 magic_docs = ''.join(magic_docs)
386 387
387 388 if mode == 'latex':
388 389 print self.format_latex(magic_docs)
389 390 return
390 391 else:
391 392 magic_docs = self.format_screen(magic_docs)
392 393
393 394 outmsg = """
394 395 IPython's 'magic' functions
395 396 ===========================
396 397
397 398 The magic function system provides a series of functions which allow you to
398 399 control the behavior of IPython itself, plus a lot of system-type
399 400 features. All these functions are prefixed with a % character, but parameters
400 401 are given without parentheses or quotes.
401 402
402 403 NOTE: If you have 'automagic' enabled (via the command line option or with the
403 404 %automagic function), you don't need to type in the % explicitly. By default,
404 405 IPython ships with automagic on, so you should only rarely need the % escape.
405 406
406 407 Example: typing '%cd mydir' (without the quotes) changes you working directory
407 408 to 'mydir', if it exists.
408 409
409 410 You can define your own magic functions to extend the system. See the supplied
410 411 ipythonrc and example-magic.py files for details (in your ipython
411 412 configuration directory, typically $HOME/.ipython/).
412 413
413 414 You can also define your own aliased names for magic functions. In your
414 415 ipythonrc file, placing a line like:
415 416
416 417 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
417 418
418 419 will define %pf as a new name for %profile.
419 420
420 421 You can also call magics in code using the ipmagic() function, which IPython
421 422 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
422 423
423 424 For a list of the available magic functions, use %lsmagic. For a description
424 425 of any of them, type %magic_name?, e.g. '%cd?'.
425 426
426 427 Currently the magic system has the following functions:\n"""
427 428
428 429 mesc = self.shell.ESC_MAGIC
429 430 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
430 431 "\n\n%s%s\n\n%s" % (outmsg,
431 432 magic_docs,mesc,mesc,
432 433 (' '+mesc).join(self.lsmagic()),
433 434 Magic.auto_status[self.shell.rc.automagic] ) )
434 435
435 436 page(outmsg,screen_lines=self.shell.rc.screen_length)
436 437
437 438 def magic_automagic(self, parameter_s = ''):
438 439 """Make magic functions callable without having to type the initial %.
439 440
440 441 Toggles on/off (when off, you must call it as %automagic, of
441 442 course). Note that magic functions have lowest priority, so if there's
442 443 a variable whose name collides with that of a magic fn, automagic
443 444 won't work for that function (you get the variable instead). However,
444 445 if you delete the variable (del var), the previously shadowed magic
445 446 function becomes visible to automagic again."""
446 447
447 448 rc = self.shell.rc
448 449 rc.automagic = not rc.automagic
449 450 print '\n' + Magic.auto_status[rc.automagic]
450 451
451 452 def magic_autocall(self, parameter_s = ''):
452 453 """Make functions callable without having to type parentheses.
453 454
454 455 This toggles the autocall command line option on and off."""
455 456
456 457 rc = self.shell.rc
457 458 rc.autocall = not rc.autocall
458 459 print "Automatic calling is:",['OFF','ON'][rc.autocall]
459 460
460 461 def magic_autoindent(self, parameter_s = ''):
461 462 """Toggle autoindent on/off (if available)."""
462 463
463 464 self.shell.set_autoindent()
464 465 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
465 466
466 467 def magic_system_verbose(self, parameter_s = ''):
467 468 """Toggle verbose printing of system calls on/off."""
468 469
469 470 self.shell.rc_set_toggle('system_verbose')
470 471 print "System verbose printing is:",\
471 472 ['OFF','ON'][self.shell.rc.system_verbose]
472 473
473 474 def magic_history(self, parameter_s = ''):
474 475 """Print input history (_i<n> variables), with most recent last.
475 476
476 477 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
477 478 %history [-n] n -> print at most n inputs\\
478 479 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
479 480
480 481 Each input's number <n> is shown, and is accessible as the
481 482 automatically generated variable _i<n>. Multi-line statements are
482 483 printed starting at a new line for easy copy/paste.
483 484
484 485 If option -n is used, input numbers are not printed. This is useful if
485 486 you want to get a printout of many lines which can be directly pasted
486 487 into a text editor.
487 488
488 489 This feature is only available if numbered prompts are in use."""
489 490
490 491 if not self.do_full_cache:
491 492 print 'This feature is only available if numbered prompts are in use.'
492 493 return
493 494 opts,args = self.parse_options(parameter_s,'n',mode='list')
494 495
495 496 default_length = 40
496 497 if len(args) == 0:
497 498 final = self.outputcache.prompt_count
498 499 init = max(1,final-default_length)
499 500 elif len(args) == 1:
500 501 final = self.outputcache.prompt_count
501 502 init = max(1,final-int(args[0]))
502 503 elif len(args) == 2:
503 504 init,final = map(int,args)
504 505 else:
505 506 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
506 507 print self.magic_hist.__doc__
507 508 return
508 509 width = len(str(final))
509 510 line_sep = ['','\n']
510 511 input_hist = self.shell.input_hist
511 512 print_nums = not opts.has_key('n')
512 513 for in_num in range(init,final):
513 514 inline = input_hist[in_num]
514 515 multiline = inline.count('\n') > 1
515 516 if print_nums:
516 517 print str(in_num).ljust(width)+':'+ line_sep[multiline],
517 518 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
518 519 inline.startswith('#!'):
519 520 print inline[1:],
520 521 else:
521 522 print inline,
522 523
523 524 def magic_hist(self, parameter_s=''):
524 525 """Alternate name for %history."""
525 526 return self.magic_history(parameter_s)
526 527
527 528 def magic_p(self, parameter_s=''):
528 529 """Just a short alias for Python's 'print'."""
529 530 exec 'print ' + parameter_s in self.shell.user_ns
530 531
531 532 def magic_r(self, parameter_s=''):
532 533 """Repeat previous input.
533 534
534 535 If given an argument, repeats the previous command which starts with
535 536 the same string, otherwise it just repeats the previous input.
536 537
537 538 Shell escaped commands (with ! as first character) are not recognized
538 539 by this system, only pure python code and magic commands.
539 540 """
540 541
541 542 start = parameter_s.strip()
542 543 esc_magic = self.shell.ESC_MAGIC
543 544 # Identify magic commands even if automagic is on (which means
544 545 # the in-memory version is different from that typed by the user).
545 546 if self.shell.rc.automagic:
546 547 start_magic = esc_magic+start
547 548 else:
548 549 start_magic = start
549 550 # Look through the input history in reverse
550 551 for n in range(len(self.shell.input_hist)-2,0,-1):
551 552 input = self.shell.input_hist[n]
552 553 # skip plain 'r' lines so we don't recurse to infinity
553 554 if input != 'ipmagic("r")\n' and \
554 555 (input.startswith(start) or input.startswith(start_magic)):
555 556 #print 'match',`input` # dbg
556 557 if input.startswith(esc_magic):
557 558 input = magic2python(input)
558 559 #print 'modified',`input` # dbg
559 560 print 'Executing:',input,
560 561 exec input in self.shell.user_ns
561 562 return
562 563 print 'No previous input matching `%s` found.' % start
563 564
564 565 def magic_page(self, parameter_s=''):
565 566 """Pretty print the object and display it through a pager.
566 567
567 568 If no parameter is given, use _ (last output)."""
568 569 # After a function contributed by Olivier Aubert, slightly modified.
569 570
570 571 oname = parameter_s and parameter_s or '_'
571 572 info = self._ofind(oname)
572 573 if info['found']:
573 574 page(pformat(info['obj']))
574 575 else:
575 576 print 'Object `%s` not found' % oname
576 577
577 578 def magic_profile(self, parameter_s=''):
578 579 """Print your currently active IPyhton profile."""
579 580 if self.shell.rc.profile:
580 581 printpl('Current IPython profile: $self.shell.rc.profile.')
581 582 else:
582 583 print 'No profile active.'
583 584
584 585 def _inspect(self,meth,oname,**kw):
585 586 """Generic interface to the inspector system.
586 587
587 588 This function is meant to be called by pdef, pdoc & friends."""
588 589
589 590 oname = oname.strip()
590 591 info = Struct(self._ofind(oname))
591 592 if info.found:
592 593 pmethod = getattr(self.shell.inspector,meth)
593 594 formatter = info.ismagic and self.format_screen or None
594 595 if meth == 'pdoc':
595 596 pmethod(info.obj,oname,formatter)
596 597 elif meth == 'pinfo':
597 598 pmethod(info.obj,oname,formatter,info,**kw)
598 599 else:
599 600 pmethod(info.obj,oname)
600 601 else:
601 602 print 'Object `%s` not found.' % oname
602 603 return 'not found' # so callers can take other action
603 604
604 605 def magic_pdef(self, parameter_s=''):
605 606 """Print the definition header for any callable object.
606 607
607 608 If the object is a class, print the constructor information."""
608 609 self._inspect('pdef',parameter_s)
609 610
610 611 def magic_pdoc(self, parameter_s=''):
611 612 """Print the docstring for an object.
612 613
613 614 If the given object is a class, it will print both the class and the
614 615 constructor docstrings."""
615 616 self._inspect('pdoc',parameter_s)
616 617
617 618 def magic_psource(self, parameter_s=''):
618 619 """Print (or run through pager) the source code for an object."""
619 620 self._inspect('psource',parameter_s)
620 621
621 622 def magic_pfile(self, parameter_s=''):
622 623 """Print (or run through pager) the file where an object is defined.
623 624
624 625 The file opens at the line where the object definition begins. IPython
625 626 will honor the environment variable PAGER if set, and otherwise will
626 627 do its best to print the file in a convenient form.
627 628
628 629 If the given argument is not an object currently defined, IPython will
629 630 try to interpret it as a filename (automatically adding a .py extension
630 631 if needed). You can thus use %pfile as a syntax highlighting code
631 632 viewer."""
632 633
633 634 # first interpret argument as an object name
634 635 out = self._inspect('pfile',parameter_s)
635 636 # if not, try the input as a filename
636 637 if out == 'not found':
637 638 try:
638 639 filename = get_py_filename(parameter_s)
639 640 except IOError,msg:
640 641 print msg
641 642 return
642 643 page(self.shell.inspector.format(file(filename).read()))
643 644
644 645 def magic_pinfo(self, parameter_s=''):
645 646 """Provide detailed information about an object.
646 647
647 648 '%pinfo object' is just a synonym for object? or ?object."""
648 649
649 650 #print 'pinfo par: <%s>' % parameter_s # dbg
650 651
651 652 # detail_level: 0 -> obj? , 1 -> obj??
652 653 detail_level = 0
653 654 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 655 # happen if the user types 'pinfo foo?' at the cmd line.
655 656 pinfo,qmark1,oname,qmark2 = \
656 657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 658 if pinfo or qmark1 or qmark2:
658 659 detail_level = 1
659 self._inspect('pinfo',oname,detail_level=detail_level)
660 if "*" in oname:
661 self.magic_psearch(oname)
662 else:
663 self._inspect('pinfo',oname,detail_level=detail_level)
664
665 def magic_psearch(self, parameter_s=''):
666 """Search for object in namespaces by wildcard.
667
668 %psearch PATTERN [OBJECT TYPE] [-NAMESPACE]* [+NAMESPACE]* [-a] [-c]
669
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 the end: both a*? and ?a* are equivalent to '%psearch a*'.
672
673 PATTERN
674
675 where PATTERN is a string containing * as a wildcard similar to its
676 use in a shell. The pattern is matched in all namespaces on the
677 search path. By default objects starting with a single _ are not
678 matched, many IPython generated objects have a single underscore. The
679 default is case insensitive matching. Matching is also done on the
680 attributes of objects and not only on the objects in a module.
681
682 [OBJECT TYPE]
683 Is the name of a python type from the types module. The name is given
684 in lowercase without the ending type, ex. StringType is written
685 string. By adding a type here only objects matching the given type are
686 matched. Using all here makes the pattern match all types (this is the
687 default).
688
689 [-NAMESPACE]* [+NAMESPACE]*
690 The possible namespaces are builtin, user, internal, alias. Where
691 builtin and user are default. Builtin contains the python module
692 builtin, user contains all imported namespaces, alias only contain the
693 shell aliases and no python objects, internal contains objects used by
694 IPython. The namespaces on the search path are removed by -namespace
695 and added by +namespace.
696
697 [-a] makes the pattern match even objects with a single underscore.
698 [-c] makes the pattern case sensitive.
699
700 Examples:
701
702 %psearch a* list objects beginning with an a
703 %psearch a* function list all functions beginning with an a
704 %psearch re.e* list objects beginning with an e in module re
705 %psearch r*.e* list objects that starts with e in modules starting in r
706 %psearch r*.* string list all strings in modules beginning with r
707
708 Case sensitve search:
709
710 %psearch a* -c list all object beginning with lower case a
711
712 Show objects beginning with a single _:
713
714 %psearch _* -a list objects beginning with underscore"""
715
716 self.shell.inspector.psearch(parameter_s,shell=self.shell)
660 717
661 718 def magic_who_ls(self, parameter_s=''):
662 719 """Return a sorted list of all interactive variables.
663 720
664 721 If arguments are given, only variables of types matching these
665 722 arguments are returned."""
666 723
667 724 user_ns = self.shell.user_ns
668 725 out = []
669 726 typelist = parameter_s.split()
670 727 for i in self.shell.user_ns.keys():
671 728 if not (i.startswith('_') or i.startswith('_i')) \
672 729 and not (self.internal_ns.has_key(i) or
673 730 self.user_config_ns.has_key(i)):
674 731 if typelist:
675 732 if type(user_ns[i]).__name__ in typelist:
676 733 out.append(i)
677 734 else:
678 735 out.append(i)
679 736 out.sort()
680 737 return out
681 738
682 739 def magic_who(self, parameter_s=''):
683 740 """Print all interactive variables, with some minimal formatting.
684 741
685 742 If any arguments are given, only variables whose type matches one of
686 743 these are printed. For example:
687 744
688 745 %who function str
689 746
690 747 will only list functions and strings, excluding all other types of
691 748 variables. To find the proper type names, simply use type(var) at a
692 749 command line to see how python prints type names. For example:
693 750
694 751 In [1]: type('hello')\\
695 752 Out[1]: <type 'str'>
696 753
697 754 indicates that the type name for strings is 'str'.
698 755
699 756 %who always excludes executed names loaded through your configuration
700 757 file and things which are internal to IPython.
701 758
702 759 This is deliberate, as typically you may load many modules and the
703 760 purpose of %who is to show you only what you've manually defined."""
704 761
705 762 varlist = self.magic_who_ls(parameter_s)
706 763 if not varlist:
707 764 print 'Interactive namespace is empty.'
708 765 return
709 766
710 767 # if we have variables, move on...
711 768
712 769 # stupid flushing problem: when prompts have no separators, stdout is
713 770 # getting lost. I'm starting to think this is a python bug. I'm having
714 771 # to force a flush with a print because even a sys.stdout.flush
715 772 # doesn't seem to do anything!
716 773
717 774 count = 0
718 775 for i in varlist:
719 776 print i+'\t',
720 777 count += 1
721 778 if count > 8:
722 779 count = 0
723 780 print
724 781 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
725 782
726 783 print # well, this does force a flush at the expense of an extra \n
727 784
728 785 def magic_whos(self, parameter_s=''):
729 786 """Like %who, but gives some extra information about each variable.
730 787
731 788 The same type filtering of %who can be applied here.
732 789
733 790 For all variables, the type is printed. Additionally it prints:
734 791
735 792 - For {},[],(): their length.
736 793
737 794 - For Numeric arrays, a summary with shape, number of elements,
738 795 typecode and size in memory.
739 796
740 797 - Everything else: a string representation, snipping their middle if
741 798 too long."""
742 799
743 800 varnames = self.magic_who_ls(parameter_s)
744 801 if not varnames:
745 802 print 'Interactive namespace is empty.'
746 803 return
747 804
748 805 # if we have variables, move on...
749 806
750 807 # for these types, show len() instead of data:
751 808 seq_types = [types.DictType,types.ListType,types.TupleType]
752 809
753 810 # for Numeric arrays, display summary info
754 811 try:
755 812 import Numeric
756 813 except ImportError:
757 814 array_type = None
758 815 else:
759 816 array_type = Numeric.ArrayType.__name__
760 817
761 818 # Find all variable names and types so we can figure out column sizes
762 819 get_vars = lambda i: self.locals[i]
763 820 type_name = lambda v: type(v).__name__
764 821 varlist = map(get_vars,varnames)
765 822 typelist = map(type_name,varlist)
766 823 # column labels and # of spaces as separator
767 824 varlabel = 'Variable'
768 825 typelabel = 'Type'
769 826 datalabel = 'Data/Info'
770 827 colsep = 3
771 828 # variable format strings
772 829 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
773 830 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
774 831 aformat = "%s: %s elems, type `%s`, %s bytes"
775 832 # find the size of the columns to format the output nicely
776 833 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
777 834 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
778 835 # table header
779 836 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
780 837 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
781 838 # and the table itself
782 839 kb = 1024
783 840 Mb = 1048576 # kb**2
784 841 for vname,var,vtype in zip(varnames,varlist,typelist):
785 842 print itpl(vformat),
786 843 if vtype in seq_types:
787 844 print len(var)
788 845 elif vtype==array_type:
789 846 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
790 847 vsize = Numeric.size(var)
791 848 vbytes = vsize*var.itemsize()
792 849 if vbytes < 100000:
793 850 print aformat % (vshape,vsize,var.typecode(),vbytes)
794 851 else:
795 852 print aformat % (vshape,vsize,var.typecode(),vbytes),
796 853 if vbytes < Mb:
797 854 print '(%s kb)' % (vbytes/kb,)
798 855 else:
799 856 print '(%s Mb)' % (vbytes/Mb,)
800 857 else:
801 858 vstr = str(var)
802 859 if len(vstr) < 50:
803 860 print vstr
804 861 else:
805 862 printpl(vfmt_short)
806 863
807 864 def magic_reset(self, parameter_s=''):
808 865 """Resets the namespace by removing all names defined by the user.
809 866
810 867 Input/Output history are left around in case you need them."""
811 868
812 869 ans = raw_input(
813 870 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
814 871 if not ans.lower() == 'y':
815 872 print 'Nothing done.'
816 873 return
817 874 for i in self.magic_who_ls():
818 875 del(self.locals[i])
819 876
820 877 def magic_config(self,parameter_s=''):
821 878 """Show IPython's internal configuration."""
822 879
823 880 page('Current configuration structure:\n'+
824 881 pformat(self.shell.rc.dict()))
825 882
826 883 def magic_logstart(self,parameter_s=''):
827 884 """Start logging anywhere in a session.
828 885
829 886 %logstart [log_name [log_mode]]
830 887
831 888 If no name is given, it defaults to a file named 'ipython.log' in your
832 889 current directory, in 'rotate' mode (see below).
833 890
834 891 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
835 892 history up to that point and then continues logging.
836 893
837 894 %logstart takes a second optional parameter: logging mode. This can be one
838 895 of (note that the modes are given unquoted):\\
839 896 over: overwrite existing log.\\
840 897 backup: rename (if exists) to name~ and start name.\\
841 898 append: well, that says it.\\
842 899 rotate: create rotating logs name.1~, name.2~, etc.
843 900 """
844 901
845 902 #FIXME. This function should all be moved to the Logger class.
846 903
847 904 valid_modes = qw('over backup append rotate')
848 905 if self.LOG:
849 906 print 'Logging is already in place. Logfile:',self.LOG
850 907 return
851 908
852 909 par = parameter_s.strip()
853 910 if not par:
854 911 logname = self.LOGDEF
855 912 logmode = 'rotate' # use rotate for the auto-generated logs
856 913 else:
857 914 try:
858 915 logname,logmode = par.split()
859 916 except:
860 917 try:
861 918 logname = par
862 919 logmode = 'backup'
863 920 except:
864 921 warn('Usage: %log [log_name [log_mode]]')
865 922 return
866 923 if not logmode in valid_modes:
867 924 warn('Logging NOT activated.\n'
868 925 'Usage: %log [log_name [log_mode]]\n'
869 926 'Valid modes: '+str(valid_modes))
870 927 return
871 928
872 929 # If we made it this far, I think we're ok:
873 930 print 'Activating auto-logging.'
874 931 print 'Current session state plus future input saved to:',logname
875 932 print 'Logging mode: ',logmode
876 933 # put logname into rc struct as if it had been called on the command line,
877 934 # so it ends up saved in the log header
878 935 # Save it in case we need to restore it...
879 936 old_logfile = self.shell.rc.opts.get('logfile','')
880 937 logname = os.path.expanduser(logname)
881 938 self.shell.rc.opts.logfile = logname
882 939 self.LOGMODE = logmode # FIXME: this should be set through a function.
883 940 try:
884 941 header = str(self.LOGHEAD)
885 942 self.create_log(header,logname)
886 943 self.logstart(header,logname)
887 944 except:
888 945 self.LOG = '' # we are NOT logging, something went wrong
889 946 self.shell.rc.opts.logfile = old_logfile
890 947 warn("Couldn't start log: "+str(sys.exc_info()[1]))
891 948 else: # log input history up to this point
892 949 self.logfile.write(self.shell.user_ns['_ih'][1:])
893 950 self.logfile.flush()
894 951
895 952 def magic_logoff(self,parameter_s=''):
896 953 """Temporarily stop logging.
897 954
898 955 You must have previously started logging."""
899 956 self.switch_log(0)
900 957
901 958 def magic_logon(self,parameter_s=''):
902 959 """Restart logging.
903 960
904 961 This function is for restarting logging which you've temporarily
905 962 stopped with %logoff. For starting logging for the first time, you
906 963 must use the %logstart function, which allows you to specify an
907 964 optional log filename."""
908 965
909 966 self.switch_log(1)
910 967
911 968 def magic_logstate(self,parameter_s=''):
912 969 """Print the status of the logging system."""
913 970
914 971 self.logstate()
915 972
916 973 def magic_pdb(self, parameter_s=''):
917 974 """Control the calling of the pdb interactive debugger.
918 975
919 976 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
920 977 argument it works as a toggle.
921 978
922 979 When an exception is triggered, IPython can optionally call the
923 980 interactive pdb debugger after the traceback printout. %pdb toggles
924 981 this feature on and off."""
925 982
926 983 par = parameter_s.strip().lower()
927 984
928 985 if par:
929 986 try:
930 987 pdb = {'off':0,'0':0,'on':1,'1':1}[par]
931 988 except KeyError:
932 989 print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.'
933 990 return
934 991 else:
935 992 self.shell.InteractiveTB.call_pdb = pdb
936 993 else:
937 994 self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb
938 995 print 'Automatic pdb calling has been turned',\
939 996 on_off(self.shell.InteractiveTB.call_pdb)
940 997
941 998
942 999 def magic_prun(self, parameter_s ='',user_mode=1,
943 1000 opts=None,arg_lst=None,prog_ns=None):
944 1001
945 1002 """Run a statement through the python code profiler.
946 1003
947 1004 Usage:\\
948 1005 %prun [options] statement
949 1006
950 1007 The given statement (which doesn't require quote marks) is run via the
951 1008 python profiler in a manner similar to the profile.run() function.
952 1009 Namespaces are internally managed to work correctly; profile.run
953 1010 cannot be used in IPython because it makes certain assumptions about
954 1011 namespaces which do not hold under IPython.
955 1012
956 1013 Options:
957 1014
958 1015 -l <limit>: you can place restrictions on what or how much of the
959 1016 profile gets printed. The limit value can be:
960 1017
961 1018 * A string: only information for function names containing this string
962 1019 is printed.
963 1020
964 1021 * An integer: only these many lines are printed.
965 1022
966 1023 * A float (between 0 and 1): this fraction of the report is printed
967 1024 (for example, use a limit of 0.4 to see the topmost 40% only).
968 1025
969 1026 You can combine several limits with repeated use of the option. For
970 1027 example, '-l __init__ -l 5' will print only the topmost 5 lines of
971 1028 information about class constructors.
972 1029
973 1030 -r: return the pstats.Stats object generated by the profiling. This
974 1031 object has all the information about the profile in it, and you can
975 1032 later use it for further analysis or in other functions.
976 1033
977 1034 Since magic functions have a particular form of calling which prevents
978 1035 you from writing something like:\\
979 1036 In [1]: p = %prun -r print 4 # invalid!\\
980 1037 you must instead use IPython's automatic variables to assign this:\\
981 1038 In [1]: %prun -r print 4 \\
982 1039 Out[1]: <pstats.Stats instance at 0x8222cec>\\
983 1040 In [2]: stats = _
984 1041
985 1042 If you really need to assign this value via an explicit function call,
986 1043 you can always tap directly into the true name of the magic function
987 1044 by using the ipmagic function (which IPython automatically adds to the
988 1045 builtins):\\
989 1046 In [3]: stats = ipmagic('prun','-r print 4')
990 1047
991 1048 You can type ipmagic? for more details on ipmagic.
992 1049
993 1050 -s <key>: sort profile by given key. You can provide more than one key
994 1051 by using the option several times: '-s key1 -s key2 -s key3...'. The
995 1052 default sorting key is 'time'.
996 1053
997 1054 The following is copied verbatim from the profile documentation
998 1055 referenced below:
999 1056
1000 1057 When more than one key is provided, additional keys are used as
1001 1058 secondary criteria when the there is equality in all keys selected
1002 1059 before them.
1003 1060
1004 1061 Abbreviations can be used for any key names, as long as the
1005 1062 abbreviation is unambiguous. The following are the keys currently
1006 1063 defined:
1007 1064
1008 1065 Valid Arg Meaning\\
1009 1066 "calls" call count\\
1010 1067 "cumulative" cumulative time\\
1011 1068 "file" file name\\
1012 1069 "module" file name\\
1013 1070 "pcalls" primitive call count\\
1014 1071 "line" line number\\
1015 1072 "name" function name\\
1016 1073 "nfl" name/file/line\\
1017 1074 "stdname" standard name\\
1018 1075 "time" internal time
1019 1076
1020 1077 Note that all sorts on statistics are in descending order (placing
1021 1078 most time consuming items first), where as name, file, and line number
1022 1079 searches are in ascending order (i.e., alphabetical). The subtle
1023 1080 distinction between "nfl" and "stdname" is that the standard name is a
1024 1081 sort of the name as printed, which means that the embedded line
1025 1082 numbers get compared in an odd way. For example, lines 3, 20, and 40
1026 1083 would (if the file names were the same) appear in the string order
1027 1084 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1028 1085 line numbers. In fact, sort_stats("nfl") is the same as
1029 1086 sort_stats("name", "file", "line").
1030 1087
1031 1088 -T <filename>: save profile results as shown on screen to a text
1032 1089 file. The profile is still shown on screen.
1033 1090
1034 1091 -D <filename>: save (via dump_stats) profile statistics to given
1035 1092 filename. This data is in a format understod by the pstats module, and
1036 1093 is generated by a call to the dump_stats() method of profile
1037 1094 objects. The profile is still shown on screen.
1038 1095
1039 1096 If you want to run complete programs under the profiler's control, use
1040 1097 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1041 1098 contains profiler specific options as described here.
1042 1099
1043 1100 You can read the complete documentation for the profile module with:\\
1044 1101 In [1]: import profile; profile.help() """
1045 1102
1046 1103 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1047 1104 # protect user quote marks
1048 1105 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1049 1106
1050 1107 if user_mode: # regular user call
1051 1108 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1052 1109 list_all=1)
1053 1110 namespace = self.shell.user_ns
1054 1111 else: # called to run a program by %run -p
1055 1112 try:
1056 1113 filename = get_py_filename(arg_lst[0])
1057 1114 except IOError,msg:
1058 1115 error(msg)
1059 1116 return
1060 1117
1061 1118 arg_str = 'execfile(filename,prog_ns)'
1062 1119 namespace = locals()
1063 1120
1064 1121 opts.merge(opts_def)
1065 1122
1066 1123 prof = profile.Profile()
1067 1124 try:
1068 1125 prof = prof.runctx(arg_str,namespace,namespace)
1069 1126 sys_exit = ''
1070 1127 except SystemExit:
1071 1128 sys_exit = """*** SystemExit exception caught in code being profiled."""
1072 1129
1073 1130 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1074 1131
1075 1132 lims = opts.l
1076 1133 if lims:
1077 1134 lims = [] # rebuild lims with ints/floats/strings
1078 1135 for lim in opts.l:
1079 1136 try:
1080 1137 lims.append(int(lim))
1081 1138 except ValueError:
1082 1139 try:
1083 1140 lims.append(float(lim))
1084 1141 except ValueError:
1085 1142 lims.append(lim)
1086 1143
1087 1144 # trap output
1088 1145 sys_stdout = sys.stdout
1089 1146 stdout_trap = StringIO()
1090 1147 try:
1091 1148 sys.stdout = stdout_trap
1092 1149 stats.print_stats(*lims)
1093 1150 finally:
1094 1151 sys.stdout = sys_stdout
1095 1152 output = stdout_trap.getvalue()
1096 1153 output = output.rstrip()
1097 1154
1098 1155 page(output,screen_lines=self.shell.rc.screen_length)
1099 1156 print sys_exit,
1100 1157
1101 1158 dump_file = opts.D[0]
1102 1159 text_file = opts.T[0]
1103 1160 if dump_file:
1104 1161 prof.dump_stats(dump_file)
1105 1162 print '\n*** Profile stats marshalled to file',\
1106 1163 `dump_file`+'.',sys_exit
1107 1164 if text_file:
1108 1165 file(text_file,'w').write(output)
1109 1166 print '\n*** Profile printout saved to text file',\
1110 1167 `text_file`+'.',sys_exit
1111 1168
1112 1169 if opts.has_key('r'):
1113 1170 return stats
1114 1171 else:
1115 1172 return None
1116 1173
1117 1174 def magic_run(self, parameter_s ='',runner=None):
1118 1175 """Run the named file inside IPython as a program.
1119 1176
1120 1177 Usage:\\
1121 1178 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1122 1179
1123 1180 Parameters after the filename are passed as command-line arguments to
1124 1181 the program (put in sys.argv). Then, control returns to IPython's
1125 1182 prompt.
1126 1183
1127 1184 This is similar to running at a system prompt:\\
1128 1185 $ python file args\\
1129 1186 but with the advantage of giving you IPython's tracebacks, and of
1130 1187 loading all variables into your interactive namespace for further use
1131 1188 (unless -p is used, see below).
1132 1189
1133 1190 The file is executed in a namespace initially consisting only of
1134 1191 __name__=='__main__' and sys.argv constructed as indicated. It thus
1135 1192 sees its environment as if it were being run as a stand-alone
1136 1193 program. But after execution, the IPython interactive namespace gets
1137 1194 updated with all variables defined in the program (except for __name__
1138 1195 and sys.argv). This allows for very convenient loading of code for
1139 1196 interactive work, while giving each program a 'clean sheet' to run in.
1140 1197
1141 1198 Options:
1142 1199
1143 1200 -n: __name__ is NOT set to '__main__', but to the running file's name
1144 1201 without extension (as python does under import). This allows running
1145 1202 scripts and reloading the definitions in them without calling code
1146 1203 protected by an ' if __name__ == "__main__" ' clause.
1147 1204
1148 1205 -i: run the file in IPython's namespace instead of an empty one. This
1149 1206 is useful if you are experimenting with code written in a text editor
1150 1207 which depends on variables defined interactively.
1151 1208
1152 1209 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1153 1210 being run. This is particularly useful if IPython is being used to
1154 1211 run unittests, which always exit with a sys.exit() call. In such
1155 1212 cases you are interested in the output of the test results, not in
1156 1213 seeing a traceback of the unittest module.
1157 1214
1158 1215 -t: print timing information at the end of the run. IPython will give
1159 1216 you an estimated CPU time consumption for your script, which under
1160 1217 Unix uses the resource module to avoid the wraparound problems of
1161 1218 time.clock(). Under Unix, an estimate of time spent on system tasks
1162 1219 is also given (for Windows platforms this is reported as 0.0).
1163 1220
1164 1221 If -t is given, an additional -N<N> option can be given, where <N>
1165 1222 must be an integer indicating how many times you want the script to
1166 1223 run. The final timing report will include total and per run results.
1167 1224
1168 1225 For example (testing the script uniq_stable.py):
1169 1226
1170 1227 In [1]: run -t uniq_stable
1171 1228
1172 1229 IPython CPU timings (estimated):\\
1173 1230 User : 0.19597 s.\\
1174 1231 System: 0.0 s.\\
1175 1232
1176 1233 In [2]: run -t -N5 uniq_stable
1177 1234
1178 1235 IPython CPU timings (estimated):\\
1179 1236 Total runs performed: 5\\
1180 1237 Times : Total Per run\\
1181 1238 User : 0.910862 s, 0.1821724 s.\\
1182 1239 System: 0.0 s, 0.0 s.
1183 1240
1184 1241 -d: run your program under the control of pdb, the Python debugger.
1185 1242 This allows you to execute your program step by step, watch variables,
1186 1243 etc. Internally, what IPython does is similar to calling:
1187 1244
1188 1245 pdb.run('execfile("YOURFILENAME")')
1189 1246
1190 1247 with a breakpoint set on line 1 of your file. You can change the line
1191 1248 number for this automatic breakpoint to be <N> by using the -bN option
1192 1249 (where N must be an integer). For example:
1193 1250
1194 1251 %run -d -b40 myscript
1195 1252
1196 1253 will set the first breakpoint at line 40 in myscript.py. Note that
1197 1254 the first breakpoint must be set on a line which actually does
1198 1255 something (not a comment or docstring) for it to stop execution.
1199 1256
1200 1257 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1201 1258 first enter 'c' (without qoutes) to start execution up to the first
1202 1259 breakpoint.
1203 1260
1204 1261 Entering 'help' gives information about the use of the debugger. You
1205 1262 can easily see pdb's full documentation with "import pdb;pdb.help()"
1206 1263 at a prompt.
1207 1264
1208 1265 -p: run program under the control of the Python profiler module (which
1209 1266 prints a detailed report of execution times, function calls, etc).
1210 1267
1211 1268 You can pass other options after -p which affect the behavior of the
1212 1269 profiler itself. See the docs for %prun for details.
1213 1270
1214 1271 In this mode, the program's variables do NOT propagate back to the
1215 1272 IPython interactive namespace (because they remain in the namespace
1216 1273 where the profiler executes them).
1217 1274
1218 1275 Internally this triggers a call to %prun, see its documentation for
1219 1276 details on the options available specifically for profiling."""
1220 1277
1221 1278 # get arguments and set sys.argv for program to be run.
1222 1279 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1223 1280 mode='list',list_all=1)
1224 1281
1225 1282 try:
1226 1283 filename = get_py_filename(arg_lst[0])
1227 1284 except IndexError:
1228 1285 warn('you must provide at least a filename.')
1229 1286 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1230 1287 return
1231 1288 except IOError,msg:
1232 1289 error(msg)
1233 1290 return
1234 1291
1235 1292 # Control the response to exit() calls made by the script being run
1236 1293 exit_ignore = opts.has_key('e')
1237 1294
1238 1295 # Make sure that the running script gets a proper sys.argv as if it
1239 1296 # were run from a system shell.
1240 1297 save_argv = sys.argv # save it for later restoring
1241 1298 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1242 1299
1243 1300 if opts.has_key('i'):
1244 1301 prog_ns = self.shell.user_ns
1245 1302 __name__save = self.shell.user_ns['__name__']
1246 1303 prog_ns['__name__'] = '__main__'
1247 1304 else:
1248 1305 if opts.has_key('n'):
1249 1306 name = os.path.splitext(os.path.basename(filename))[0]
1250 1307 else:
1251 1308 name = '__main__'
1252 1309 prog_ns = {'__name__':name}
1253 1310
1254 1311 # pickle fix. See iplib for an explanation
1255 1312 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1256 1313
1257 1314 stats = None
1258 1315 try:
1259 1316 if opts.has_key('p'):
1260 1317 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1261 1318 else:
1262 1319 if opts.has_key('d'):
1263 1320 deb = pdb.Pdb()
1264 1321 # reset Breakpoint state, which is moronically kept
1265 1322 # in a class
1266 1323 bdb.Breakpoint.next = 1
1267 1324 bdb.Breakpoint.bplist = {}
1268 1325 bdb.Breakpoint.bpbynumber = [None]
1269 1326 # Set an initial breakpoint to stop execution
1270 1327 maxtries = 10
1271 1328 bp = int(opts.get('b',[1])[0])
1272 1329 checkline = deb.checkline(filename,bp)
1273 1330 if not checkline:
1274 1331 for bp in range(bp+1,bp+maxtries+1):
1275 1332 if deb.checkline(filename,bp):
1276 1333 break
1277 1334 else:
1278 1335 msg = ("\nI failed to find a valid line to set "
1279 1336 "a breakpoint\n"
1280 1337 "after trying up to line: %s.\n"
1281 1338 "Please set a valid breakpoint manually "
1282 1339 "with the -b option." % bp)
1283 1340 error(msg)
1284 1341 return
1285 1342 # if we find a good linenumber, set the breakpoint
1286 1343 deb.do_break('%s:%s' % (filename,bp))
1287 1344 # Start file run
1288 1345 print "NOTE: Enter 'c' at the",
1289 1346 print "(Pdb) prompt to start your script."
1290 1347 deb.run('execfile("%s")' % filename,prog_ns)
1291 1348 else:
1292 1349 if runner is None:
1293 1350 runner = self.shell.safe_execfile
1294 1351 if opts.has_key('t'):
1295 1352 try:
1296 1353 nruns = int(opts['N'][0])
1297 1354 if nruns < 1:
1298 1355 error('Number of runs must be >=1')
1299 1356 return
1300 1357 except (KeyError):
1301 1358 nruns = 1
1302 1359 if nruns == 1:
1303 1360 t0 = clock2()
1304 1361 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1305 1362 t1 = clock2()
1306 1363 t_usr = t1[0]-t0[0]
1307 1364 t_sys = t1[1]-t1[1]
1308 1365 print "\nIPython CPU timings (estimated):"
1309 1366 print " User : %10s s." % t_usr
1310 1367 print " System: %10s s." % t_sys
1311 1368 else:
1312 1369 runs = range(nruns)
1313 1370 t0 = clock2()
1314 1371 for nr in runs:
1315 1372 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1316 1373 t1 = clock2()
1317 1374 t_usr = t1[0]-t0[0]
1318 1375 t_sys = t1[1]-t1[1]
1319 1376 print "\nIPython CPU timings (estimated):"
1320 1377 print "Total runs performed:",nruns
1321 1378 print " Times : %10s %10s" % ('Total','Per run')
1322 1379 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1323 1380 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1324 1381
1325 1382 else:
1326 1383 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1327 1384 if opts.has_key('i'):
1328 1385 self.shell.user_ns['__name__'] = __name__save
1329 1386 else:
1330 1387 # update IPython interactive namespace
1331 1388 del prog_ns['__name__']
1332 1389 self.shell.user_ns.update(prog_ns)
1333 1390 finally:
1334 1391 sys.argv = save_argv
1335 1392 return stats
1336 1393
1337 1394 def magic_runlog(self, parameter_s =''):
1338 1395 """Run files as logs.
1339 1396
1340 1397 Usage:\\
1341 1398 %runlog file1 file2 ...
1342 1399
1343 1400 Run the named files (treating them as log files) in sequence inside
1344 1401 the interpreter, and return to the prompt. This is much slower than
1345 1402 %run because each line is executed in a try/except block, but it
1346 1403 allows running files with syntax errors in them.
1347 1404
1348 1405 Normally IPython will guess when a file is one of its own logfiles, so
1349 1406 you can typically use %run even for logs. This shorthand allows you to
1350 1407 force any file to be treated as a log file."""
1351 1408
1352 1409 for f in parameter_s.split():
1353 1410 self.shell.safe_execfile(f,self.shell.user_ns,
1354 1411 self.shell.user_ns,islog=1)
1355 1412
1356 1413 def magic_time(self,parameter_s = ''):
1357 1414 """Time execution of a Python statement or expression.
1358 1415
1359 1416 The CPU and wall clock times are printed, and the value of the
1360 1417 expression (if any) is returned. Note that under Win32, system time
1361 1418 is always reported as 0, since it can not be measured.
1362 1419
1363 1420 This function provides very basic timing functionality. In Python
1364 1421 2.3, the timeit module offers more control and sophistication, but for
1365 1422 now IPython supports Python 2.2, so we can not rely on timeit being
1366 1423 present.
1367 1424
1368 1425 Some examples:
1369 1426
1370 1427 In [1]: time 2**128
1371 1428 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1372 1429 Wall time: 0.00
1373 1430 Out[1]: 340282366920938463463374607431768211456L
1374 1431
1375 1432 In [2]: n = 1000000
1376 1433
1377 1434 In [3]: time sum(range(n))
1378 1435 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1379 1436 Wall time: 1.37
1380 1437 Out[3]: 499999500000L
1381 1438
1382 1439 In [4]: time print 'hello world'
1383 1440 hello world
1384 1441 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1385 1442 Wall time: 0.00
1386 1443 """
1387 1444
1388 1445 # fail immediately if the given expression can't be compiled
1389 1446 try:
1390 1447 mode = 'eval'
1391 1448 code = compile(parameter_s,'<timed eval>',mode)
1392 1449 except SyntaxError:
1393 1450 mode = 'exec'
1394 1451 code = compile(parameter_s,'<timed exec>',mode)
1395 1452 # skew measurement as little as possible
1396 1453 glob = self.shell.user_ns
1397 1454 clk = clock2
1398 1455 wtime = time.time
1399 1456 # time execution
1400 1457 wall_st = wtime()
1401 1458 if mode=='eval':
1402 1459 st = clk()
1403 1460 out = eval(code,glob)
1404 1461 end = clk()
1405 1462 else:
1406 1463 st = clk()
1407 1464 exec code in glob
1408 1465 end = clk()
1409 1466 out = None
1410 1467 wall_end = wtime()
1411 1468 # Compute actual times and report
1412 1469 wall_time = wall_end-wall_st
1413 1470 cpu_user = end[0]-st[0]
1414 1471 cpu_sys = end[1]-st[1]
1415 1472 cpu_tot = cpu_user+cpu_sys
1416 1473 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1417 1474 (cpu_user,cpu_sys,cpu_tot)
1418 1475 print "Wall time: %.2f" % wall_time
1419 1476 return out
1420 1477
1421 1478 def magic_macro(self,parameter_s = ''):
1422 1479 """Define a set of input lines as a macro for future re-execution.
1423 1480
1424 1481 Usage:\\
1425 1482 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1426 1483
1427 1484 This will define a global variable called `name` which is a string
1428 1485 made of joining the slices and lines you specify (n1,n2,... numbers
1429 1486 above) from your input history into a single string. This variable
1430 1487 acts like an automatic function which re-executes those lines as if
1431 1488 you had typed them. You just type 'name' at the prompt and the code
1432 1489 executes.
1433 1490
1434 1491 Note that the slices use the standard Python slicing notation (5:8
1435 1492 means include lines numbered 5,6,7).
1436 1493
1437 1494 For example, if your history contains (%hist prints it):
1438 1495
1439 1496 44: x=1\\
1440 1497 45: y=3\\
1441 1498 46: z=x+y\\
1442 1499 47: print x\\
1443 1500 48: a=5\\
1444 1501 49: print 'x',x,'y',y\\
1445 1502
1446 1503 you can create a macro with lines 44 through 47 (included) and line 49
1447 1504 called my_macro with:
1448 1505
1449 1506 In [51]: %macro my_macro 44:48 49
1450 1507
1451 1508 Now, typing `my_macro` (without quotes) will re-execute all this code
1452 1509 in one pass.
1453 1510
1454 1511 You don't need to give the line-numbers in order, and any given line
1455 1512 number can appear multiple times. You can assemble macros with any
1456 1513 lines from your input history in any order.
1457 1514
1458 1515 The macro is a simple object which holds its value in an attribute,
1459 1516 but IPython's display system checks for macros and executes them as
1460 1517 code instead of printing them when you type their name.
1461 1518
1462 1519 You can view a macro's contents by explicitly printing it with:
1463 1520
1464 1521 'print macro_name'.
1465 1522
1466 1523 For one-off cases which DON'T contain magic function calls in them you
1467 1524 can obtain similar results by explicitly executing slices from your
1468 1525 input history with:
1469 1526
1470 1527 In [60]: exec In[44:48]+In[49]"""
1471 1528
1472 1529 args = parameter_s.split()
1473 1530 name,ranges = args[0], args[1:]
1474 1531 #print 'rng',ranges # dbg
1475 1532 cmds = self.extract_input_slices(ranges)
1476 1533 macro = Macro(cmds)
1477 1534 self.shell.user_ns.update({name:macro})
1478 1535 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1479 1536 print 'Macro contents:'
1480 1537 print str(macro).rstrip(),
1481 1538
1482 1539 def magic_save(self,parameter_s = ''):
1483 1540 """Save a set of lines to a given filename.
1484 1541
1485 1542 Usage:\\
1486 1543 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1487 1544
1488 1545 This function uses the same syntax as %macro for line extraction, but
1489 1546 instead of creating a macro it saves the resulting string to the
1490 1547 filename you specify.
1491 1548
1492 1549 It adds a '.py' extension to the file if you don't do so yourself, and
1493 1550 it asks for confirmation before overwriting existing files."""
1494 1551
1495 1552 args = parameter_s.split()
1496 1553 fname,ranges = args[0], args[1:]
1497 1554 if not fname.endswith('.py'):
1498 1555 fname += '.py'
1499 1556 if os.path.isfile(fname):
1500 1557 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1501 1558 if ans.lower() not in ['y','yes']:
1502 1559 print 'Operation cancelled.'
1503 1560 return
1504 1561 cmds = ''.join(self.extract_input_slices(ranges))
1505 1562 f = file(fname,'w')
1506 1563 f.write(cmds)
1507 1564 f.close()
1508 1565 print 'The following commands were written to file `%s`:' % fname
1509 1566 print cmds
1510 1567
1511 1568 def magic_ed(self,parameter_s = ''):
1512 1569 """Alias to %edit."""
1513 1570 return self.magic_edit(parameter_s)
1514 1571
1515 1572 def magic_edit(self,parameter_s = '',last_call=['','']):
1516 1573 """Bring up an editor and execute the resulting code.
1517 1574
1518 1575 Usage:
1519 1576 %edit [options] [args]
1520 1577
1521 1578 %edit runs IPython's editor hook. The default version of this hook is
1522 1579 set to call the __IPYTHON__.rc.editor command. This is read from your
1523 1580 environment variable $EDITOR. If this isn't found, it will default to
1524 1581 vi under Linux/Unix and to notepad under Windows. See the end of this
1525 1582 docstring for how to change the editor hook.
1526 1583
1527 1584 You can also set the value of this editor via the command line option
1528 1585 '-editor' or in your ipythonrc file. This is useful if you wish to use
1529 1586 specifically for IPython an editor different from your typical default
1530 1587 (and for Windows users who typically don't set environment variables).
1531 1588
1532 1589 This command allows you to conveniently edit multi-line code right in
1533 1590 your IPython session.
1534 1591
1535 1592 If called without arguments, %edit opens up an empty editor with a
1536 1593 temporary file and will execute the contents of this file when you
1537 1594 close it (don't forget to save it!).
1538 1595
1539 1596 Options:
1540 1597
1541 1598 -p: this will call the editor with the same data as the previous time
1542 1599 it was used, regardless of how long ago (in your current session) it
1543 1600 was.
1544 1601
1545 1602 -x: do not execute the edited code immediately upon exit. This is
1546 1603 mainly useful if you are editing programs which need to be called with
1547 1604 command line arguments, which you can then do using %run.
1548 1605
1549 1606 Arguments:
1550 1607
1551 1608 If arguments are given, the following possibilites exist:
1552 1609
1553 1610 - The arguments are numbers or pairs of colon-separated numbers (like
1554 1611 1 4:8 9). These are interpreted as lines of previous input to be
1555 1612 loaded into the editor. The syntax is the same of the %macro command.
1556 1613
1557 1614 - If the argument doesn't start with a number, it is evaluated as a
1558 1615 variable and its contents loaded into the editor. You can thus edit
1559 1616 any string which contains python code (including the result of
1560 1617 previous edits).
1561 1618
1562 1619 - If the argument is the name of an object (other than a string),
1563 1620 IPython will try to locate the file where it was defined and open the
1564 1621 editor at the point where it is defined. You can use `%edit function`
1565 1622 to load an editor exactly at the point where 'function' is defined,
1566 1623 edit it and have the file be executed automatically.
1567 1624
1568 1625 Note: opening at an exact line is only supported under Unix, and some
1569 1626 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1570 1627 '+NUMBER' parameter necessary for this feature. Good editors like
1571 1628 (X)Emacs, vi, jed, pico and joe all do.
1572 1629
1573 1630 - If the argument is not found as a variable, IPython will look for a
1574 1631 file with that name (adding .py if necessary) and load it into the
1575 1632 editor. It will execute its contents with execfile() when you exit,
1576 1633 loading any code in the file into your interactive namespace.
1577 1634
1578 1635 After executing your code, %edit will return as output the code you
1579 1636 typed in the editor (except when it was an existing file). This way
1580 1637 you can reload the code in further invocations of %edit as a variable,
1581 1638 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1582 1639 the output.
1583 1640
1584 1641 Note that %edit is also available through the alias %ed.
1585 1642
1586 1643 This is an example of creating a simple function inside the editor and
1587 1644 then modifying it. First, start up the editor:
1588 1645
1589 1646 In [1]: ed\\
1590 1647 Editing... done. Executing edited code...\\
1591 1648 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1592 1649
1593 1650 We can then call the function foo():
1594 1651
1595 1652 In [2]: foo()\\
1596 1653 foo() was defined in an editing session
1597 1654
1598 1655 Now we edit foo. IPython automatically loads the editor with the
1599 1656 (temporary) file where foo() was previously defined:
1600 1657
1601 1658 In [3]: ed foo\\
1602 1659 Editing... done. Executing edited code...
1603 1660
1604 1661 And if we call foo() again we get the modified version:
1605 1662
1606 1663 In [4]: foo()\\
1607 1664 foo() has now been changed!
1608 1665
1609 1666 Here is an example of how to edit a code snippet successive
1610 1667 times. First we call the editor:
1611 1668
1612 1669 In [8]: ed\\
1613 1670 Editing... done. Executing edited code...\\
1614 1671 hello\\
1615 1672 Out[8]: "print 'hello'\\n"
1616 1673
1617 1674 Now we call it again with the previous output (stored in _):
1618 1675
1619 1676 In [9]: ed _\\
1620 1677 Editing... done. Executing edited code...\\
1621 1678 hello world\\
1622 1679 Out[9]: "print 'hello world'\\n"
1623 1680
1624 1681 Now we call it with the output #8 (stored in _8, also as Out[8]):
1625 1682
1626 1683 In [10]: ed _8\\
1627 1684 Editing... done. Executing edited code...\\
1628 1685 hello again\\
1629 1686 Out[10]: "print 'hello again'\\n"
1630 1687
1631 1688
1632 1689 Changing the default editor hook:
1633 1690
1634 1691 If you wish to write your own editor hook, you can put it in a
1635 1692 configuration file which you load at startup time. The default hook
1636 1693 is defined in the IPython.hooks module, and you can use that as a
1637 1694 starting example for further modifications. That file also has
1638 1695 general instructions on how to set a new hook for use once you've
1639 1696 defined it."""
1640 1697
1641 1698 # FIXME: This function has become a convoluted mess. It needs a
1642 1699 # ground-up rewrite with clean, simple logic.
1643 1700
1644 1701 def make_filename(arg):
1645 1702 "Make a filename from the given args"
1646 1703 try:
1647 1704 filename = get_py_filename(arg)
1648 1705 except IOError:
1649 1706 if args.endswith('.py'):
1650 1707 filename = arg
1651 1708 else:
1652 1709 filename = None
1653 1710 return filename
1654 1711
1655 1712 # custom exceptions
1656 1713 class DataIsObject(Exception): pass
1657 1714
1658 1715 opts,args = self.parse_options(parameter_s,'px')
1659 1716
1660 1717 # Default line number value
1661 1718 lineno = None
1662 1719 if opts.has_key('p'):
1663 1720 args = '_%s' % last_call[0]
1664 1721 if not self.shell.user_ns.has_key(args):
1665 1722 args = last_call[1]
1666 1723
1667 1724 # use last_call to remember the state of the previous call, but don't
1668 1725 # let it be clobbered by successive '-p' calls.
1669 1726 try:
1670 1727 last_call[0] = self.shell.outputcache.prompt_count
1671 1728 if not opts.has_key('p'):
1672 1729 last_call[1] = parameter_s
1673 1730 except:
1674 1731 pass
1675 1732
1676 1733 # by default this is done with temp files, except when the given
1677 1734 # arg is a filename
1678 1735 use_temp = 1
1679 1736
1680 1737 if re.match(r'\d',args):
1681 1738 # Mode where user specifies ranges of lines, like in %macro.
1682 1739 # This means that you can't edit files whose names begin with
1683 1740 # numbers this way. Tough.
1684 1741 ranges = args.split()
1685 1742 data = ''.join(self.extract_input_slices(ranges))
1686 1743 elif args.endswith('.py'):
1687 1744 filename = make_filename(args)
1688 1745 data = ''
1689 1746 use_temp = 0
1690 1747 elif args:
1691 1748 try:
1692 1749 # Load the parameter given as a variable. If not a string,
1693 1750 # process it as an object instead (below)
1694 1751
1695 1752 #print '*** args',args,'type',type(args) # dbg
1696 1753 data = eval(args,self.shell.user_ns)
1697 1754 if not type(data) in StringTypes:
1698 1755 raise DataIsObject
1699 1756 except (NameError,SyntaxError):
1700 1757 # given argument is not a variable, try as a filename
1701 1758 filename = make_filename(args)
1702 1759 if filename is None:
1703 1760 warn("Argument given (%s) can't be found as a variable "
1704 1761 "or as a filename." % args)
1705 1762 return
1706 1763 data = ''
1707 1764 use_temp = 0
1708 1765 except DataIsObject:
1709 1766 # For objects, try to edit the file where they are defined
1710 1767 try:
1711 1768 filename = inspect.getabsfile(data)
1712 1769 datafile = 1
1713 1770 except TypeError:
1714 1771 filename = make_filename(args)
1715 1772 datafile = 1
1716 1773 warn('Could not find file where `%s` is defined.\n'
1717 1774 'Opening a file named `%s`' % (args,filename))
1718 1775 # Now, make sure we can actually read the source (if it was in
1719 1776 # a temp file it's gone by now).
1720 1777 if datafile:
1721 1778 try:
1722 1779 lineno = inspect.getsourcelines(data)[1]
1723 1780 except IOError:
1724 1781 filename = make_filename(args)
1725 1782 if filename is None:
1726 1783 warn('The file `%s` where `%s` was defined cannot '
1727 1784 'be read.' % (filename,data))
1728 1785 return
1729 1786 use_temp = 0
1730 1787 else:
1731 1788 data = ''
1732 1789
1733 1790 if use_temp:
1734 1791 filename = tempfile.mktemp('.py')
1735 1792 self.shell.tempfiles.append(filename)
1736 1793
1737 1794 if data and use_temp:
1738 1795 tmp_file = open(filename,'w')
1739 1796 tmp_file.write(data)
1740 1797 tmp_file.close()
1741 1798
1742 1799 # do actual editing here
1743 1800 print 'Editing...',
1744 1801 sys.stdout.flush()
1745 1802 self.shell.hooks.editor(filename,lineno)
1746 1803 if opts.has_key('x'): # -x prevents actual execution
1747 1804 print
1748 1805 else:
1749 1806 print 'done. Executing edited code...'
1750 1807 try:
1751 1808 execfile(filename,self.shell.user_ns)
1752 1809 except IOError,msg:
1753 1810 if msg.filename == filename:
1754 1811 warn('File not found. Did you forget to save?')
1755 1812 return
1756 1813 else:
1757 1814 self.shell.showtraceback()
1758 1815 except:
1759 1816 self.shell.showtraceback()
1760 1817 if use_temp:
1761 1818 contents = open(filename).read()
1762 1819 return contents
1763 1820
1764 1821 def magic_xmode(self,parameter_s = ''):
1765 1822 """Switch modes for the exception handlers.
1766 1823
1767 1824 Valid modes: Plain, Context and Verbose.
1768 1825
1769 1826 If called without arguments, acts as a toggle."""
1770 1827
1771 1828 new_mode = parameter_s.strip().capitalize()
1772 1829 try:
1773 1830 self.InteractiveTB.set_mode(mode = new_mode)
1774 1831 print 'Exception reporting mode:',self.InteractiveTB.mode
1775 1832 except:
1776 1833 warn('Error changing exception modes.\n' + str(sys.exc_info()[1]))
1777 1834
1778 1835 def magic_colors(self,parameter_s = ''):
1779 1836 """Switch color scheme for prompts, info system and exception handlers.
1780 1837
1781 1838 Currently implemented schemes: NoColor, Linux, LightBG.
1782 1839
1783 1840 Color scheme names are not case-sensitive."""
1784 1841
1785 1842 new_scheme = parameter_s.strip()
1786 1843 if not new_scheme:
1787 1844 print 'You must specify a color scheme.'
1788 1845 return
1789 1846 # Under Windows, check for Gary Bishop's readline, which is necessary
1790 1847 # for ANSI coloring
1791 1848 if os.name in ['nt','dos']:
1792 1849 try:
1793 1850 import readline
1794 1851 except ImportError:
1795 1852 has_readline = 0
1796 1853 else:
1797 1854 try:
1798 1855 readline.GetOutputFile()
1799 1856 except AttributeError:
1800 1857 has_readline = 0
1801 1858 else:
1802 1859 has_readline = 1
1803 1860 if not has_readline:
1804 1861 msg = """\
1805 1862 Proper color support under MS Windows requires Gary Bishop's readline library.
1806 1863 You can find it at:
1807 1864 http://sourceforge.net/projects/uncpythontools
1808 1865 Gary's readline needs the ctypes module, from:
1809 1866 http://starship.python.net/crew/theller/ctypes
1810 1867
1811 1868 Defaulting color scheme to 'NoColor'"""
1812 1869 new_scheme = 'NoColor'
1813 1870 warn(msg)
1814 1871
1815 1872 # Set prompt colors
1816 1873 try:
1817 1874 self.shell.outputcache.set_colors(new_scheme)
1818 1875 except:
1819 1876 warn('Error changing prompt color schemes.\n'
1820 1877 + str(sys.exc_info()[1]))
1821 1878 else:
1822 1879 self.shell.rc.colors = \
1823 1880 self.shell.outputcache.color_table.active_scheme_name
1824 1881 # Set exception colors
1825 1882 try:
1826 1883 self.shell.InteractiveTB.set_colors(scheme = new_scheme)
1827 1884 self.shell.SyntaxTB.set_colors(scheme = new_scheme)
1828 1885 except:
1829 1886 warn('Error changing exception color schemes.\n'
1830 1887 + str(sys.exc_info()[1]))
1831 1888 # Set info (for 'object?') colors
1832 1889 if self.shell.rc.color_info:
1833 1890 try:
1834 1891 self.shell.inspector.set_active_scheme(new_scheme)
1835 1892 except:
1836 1893 warn('Error changing object inspector color schemes.\n'
1837 1894 + str(sys.exc_info()[1]))
1838 1895 else:
1839 1896 self.shell.inspector.set_active_scheme('NoColor')
1840 1897
1841 1898 def magic_color_info(self,parameter_s = ''):
1842 1899 """Toggle color_info.
1843 1900
1844 1901 The color_info configuration parameter controls whether colors are
1845 1902 used for displaying object details (by things like %psource, %pfile or
1846 1903 the '?' system). This function toggles this value with each call.
1847 1904
1848 1905 Note that unless you have a fairly recent pager (less works better
1849 1906 than more) in your system, using colored object information displays
1850 1907 will not work properly. Test it and see."""
1851 1908
1852 1909 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1853 1910 self.magic_colors(self.shell.rc.colors)
1854 1911 print 'Object introspection functions have now coloring:',
1855 1912 print ['OFF','ON'][self.shell.rc.color_info]
1856 1913
1857 1914 def magic_Pprint(self, parameter_s=''):
1858 1915 """Toggle pretty printing on/off."""
1859 1916
1860 1917 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1861 1918 print 'Pretty printing has been turned', \
1862 1919 ['OFF','ON'][self.shell.outputcache.Pprint]
1863 1920
1864 1921 def magic_Exit(self, parameter_s=''):
1865 1922 """Exit IPython without confirmation."""
1866 1923
1867 1924 self.shell.exit_now = True
1868 1925
1869 1926 def magic_Quit(self, parameter_s=''):
1870 1927 """Exit IPython without confirmation (like %Exit)."""
1871 1928
1872 1929 self.shell.exit_now = True
1873 1930
1874 1931 #......................................................................
1875 1932 # Functions to implement unix shell-type things
1876 1933
1877 1934 def magic_alias(self, parameter_s = ''):
1878 1935 """Define an alias for a system command.
1879 1936
1880 1937 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
1881 1938
1882 1939 Then, typing 'alias_name params' will execute the system command 'cmd
1883 1940 params' (from your underlying operating system).
1884 1941
1885 1942 Aliases have lower precedence than magic functions and Python normal
1886 1943 variables, so if 'foo' is both a Python variable and an alias, the
1887 1944 alias can not be executed until 'del foo' removes the Python variable.
1888 1945
1889 1946 You can use the %l specifier in an alias definition to represent the
1890 1947 whole line when the alias is called. For example:
1891 1948
1892 1949 In [2]: alias all echo "Input in brackets: <%l>"\\
1893 1950 In [3]: all hello world\\
1894 1951 Input in brackets: <hello world>
1895 1952
1896 1953 You can also define aliases with parameters using %s specifiers (one
1897 1954 per parameter):
1898 1955
1899 1956 In [1]: alias parts echo first %s second %s\\
1900 1957 In [2]: %parts A B\\
1901 1958 first A second B\\
1902 1959 In [3]: %parts A\\
1903 1960 Incorrect number of arguments: 2 expected.\\
1904 1961 parts is an alias to: 'echo first %s second %s'
1905 1962
1906 1963 Note that %l and %s are mutually exclusive. You can only use one or
1907 1964 the other in your aliases.
1908 1965
1909 1966 Aliases expand Python variables just like system calls using ! or !!
1910 1967 do: all expressions prefixed with '$' get expanded. For details of
1911 1968 the semantic rules, see PEP-215:
1912 1969 http://www.python.org/peps/pep-0215.html. This is the library used by
1913 1970 IPython for variable expansion. If you want to access a true shell
1914 1971 variable, an extra $ is necessary to prevent its expansion by IPython:
1915 1972
1916 1973 In [6]: alias show echo\\
1917 1974 In [7]: PATH='A Python string'\\
1918 1975 In [8]: show $PATH\\
1919 1976 A Python string\\
1920 1977 In [9]: show $$PATH\\
1921 1978 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1922 1979
1923 1980 You can use the alias facility to acess all of $PATH. See the %rehash
1924 1981 and %rehashx functions, which automatically create aliases for the
1925 1982 contents of your $PATH.
1926 1983
1927 1984 If called with no parameters, %alias prints the current alias table."""
1928 1985
1929 1986 par = parameter_s.strip()
1930 1987 if not par:
1931 1988 if self.shell.rc.automagic:
1932 1989 prechar = ''
1933 1990 else:
1934 1991 prechar = self.shell.ESC_MAGIC
1935 1992 print 'Alias\t\tSystem Command\n'+'-'*30
1936 1993 atab = self.shell.alias_table
1937 1994 aliases = atab.keys()
1938 1995 aliases.sort()
1939 1996 for alias in aliases:
1940 1997 print prechar+alias+'\t\t'+atab[alias][1]
1941 1998 print '-'*30+'\nTotal number of aliases:',len(aliases)
1942 1999 return
1943 2000 try:
1944 2001 alias,cmd = par.split(None,1)
1945 2002 except:
1946 2003 print OInspect.getdoc(self.magic_alias)
1947 2004 else:
1948 2005 nargs = cmd.count('%s')
1949 2006 if nargs>0 and cmd.find('%l')>=0:
1950 2007 error('The %s and %l specifiers are mutually exclusive '
1951 2008 'in alias definitions.')
1952 2009 else: # all looks OK
1953 2010 self.shell.alias_table[alias] = (nargs,cmd)
1954 2011 self.shell.alias_table_validate(verbose=1)
1955 2012 # end magic_alias
1956 2013
1957 2014 def magic_unalias(self, parameter_s = ''):
1958 2015 """Remove an alias"""
1959 2016
1960 2017 aname = parameter_s.strip()
1961 2018 if aname in self.shell.alias_table:
1962 2019 del self.shell.alias_table[aname]
1963 2020
1964 2021 def magic_rehash(self, parameter_s = ''):
1965 2022 """Update the alias table with all entries in $PATH.
1966 2023
1967 2024 This version does no checks on execute permissions or whether the
1968 2025 contents of $PATH are truly files (instead of directories or something
1969 2026 else). For such a safer (but slower) version, use %rehashx."""
1970 2027
1971 2028 # This function (and rehashx) manipulate the alias_table directly
1972 2029 # rather than calling magic_alias, for speed reasons. A rehash on a
1973 2030 # typical Linux box involves several thousand entries, so efficiency
1974 2031 # here is a top concern.
1975 2032
1976 2033 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
1977 2034 alias_table = self.shell.alias_table
1978 2035 for pdir in path:
1979 2036 for ff in os.listdir(pdir):
1980 2037 # each entry in the alias table must be (N,name), where
1981 2038 # N is the number of positional arguments of the alias.
1982 2039 alias_table[ff] = (0,ff)
1983 2040 # Make sure the alias table doesn't contain keywords or builtins
1984 2041 self.shell.alias_table_validate()
1985 2042 # Call again init_auto_alias() so we get 'rm -i' and other modified
1986 2043 # aliases since %rehash will probably clobber them
1987 2044 self.shell.init_auto_alias()
1988 2045
1989 2046 def magic_rehashx(self, parameter_s = ''):
1990 2047 """Update the alias table with all executable files in $PATH.
1991 2048
1992 2049 This version explicitly checks that every entry in $PATH is a file
1993 2050 with execute access (os.X_OK), so it is much slower than %rehash.
1994 2051
1995 2052 Under Windows, it checks executability as a match agains a
1996 2053 '|'-separated string of extensions, stored in the IPython config
1997 2054 variable win_exec_ext. This defaults to 'exe|com|bat'. """
1998 2055
1999 2056 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2000 2057 alias_table = self.shell.alias_table
2001 2058
2002 2059 if os.name == 'posix':
2003 2060 isexec = lambda fname:os.path.isfile(fname) and \
2004 2061 os.access(fname,os.X_OK)
2005 2062 else:
2006 2063
2007 2064 try:
2008 2065 winext = os.environ['pathext'].replace(';','|').replace('.','')
2009 2066 except KeyError:
2010 2067 winext = 'exe|com|bat'
2011 2068
2012 2069 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2013 2070 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2014 2071 savedir = os.getcwd()
2015 2072 try:
2016 2073 # write the whole loop for posix/Windows so we don't have an if in
2017 2074 # the innermost part
2018 2075 if os.name == 'posix':
2019 2076 for pdir in path:
2020 2077 os.chdir(pdir)
2021 2078 for ff in os.listdir(pdir):
2022 2079 if isexec(ff):
2023 2080 # each entry in the alias table must be (N,name),
2024 2081 # where N is the number of positional arguments of the
2025 2082 # alias.
2026 2083 alias_table[ff] = (0,ff)
2027 2084 else:
2028 2085 for pdir in path:
2029 2086 os.chdir(pdir)
2030 2087 for ff in os.listdir(pdir):
2031 2088 if isexec(ff):
2032 2089 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2033 2090 # Make sure the alias table doesn't contain keywords or builtins
2034 2091 self.shell.alias_table_validate()
2035 2092 # Call again init_auto_alias() so we get 'rm -i' and other
2036 2093 # modified aliases since %rehashx will probably clobber them
2037 2094 self.shell.init_auto_alias()
2038 2095 finally:
2039 2096 os.chdir(savedir)
2040 2097
2041 2098 def magic_pwd(self, parameter_s = ''):
2042 2099 """Return the current working directory path."""
2043 2100 return os.getcwd()
2044 2101
2045 2102 def magic_cd(self, parameter_s=''):
2046 2103 """Change the current working directory.
2047 2104
2048 2105 This command automatically maintains an internal list of directories
2049 2106 you visit during your IPython session, in the variable _dh. The
2050 2107 command %dhist shows this history nicely formatted.
2051 2108
2052 2109 Usage:
2053 2110
2054 2111 cd 'dir': changes to directory 'dir'.
2055 2112
2056 2113 cd -: changes to the last visited directory.
2057 2114
2058 2115 cd -<n>: changes to the n-th directory in the directory history.
2059 2116
2060 2117 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2061 2118 (note: cd <bookmark_name> is enough if there is no
2062 2119 directory <bookmark_name>, but a bookmark with the name exists.)
2063 2120
2064 2121 Options:
2065 2122
2066 2123 -q: quiet. Do not print the working directory after the cd command is
2067 2124 executed. By default IPython's cd command does print this directory,
2068 2125 since the default prompts do not display path information.
2069 2126
2070 2127 Note that !cd doesn't work for this purpose because the shell where
2071 2128 !command runs is immediately discarded after executing 'command'."""
2072 2129
2073 2130 parameter_s = parameter_s.strip()
2074 2131 bkms = self.shell.persist.get("bookmarks",{})
2075 2132
2076 2133 numcd = re.match(r'(-)(\d+)$',parameter_s)
2077 2134 # jump in directory history by number
2078 2135 if numcd:
2079 2136 nn = int(numcd.group(2))
2080 2137 try:
2081 2138 ps = self.shell.user_ns['_dh'][nn]
2082 2139 except IndexError:
2083 2140 print 'The requested directory does not exist in history.'
2084 2141 return
2085 2142 else:
2086 2143 opts = {}
2087 2144 else:
2088 2145 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2089 2146 # jump to previous
2090 2147 if ps == '-':
2091 2148 try:
2092 2149 ps = self.shell.user_ns['_dh'][-2]
2093 2150 except IndexError:
2094 2151 print 'No previous directory to change to.'
2095 2152 return
2096 2153 # jump to bookmark
2097 2154 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2098 2155 if bkms.has_key(ps):
2099 2156 target = bkms[ps]
2100 2157 print '(bookmark:%s) -> %s' % (ps,target)
2101 2158 ps = target
2102 2159 else:
2103 2160 if bkms:
2104 2161 error("Bookmark '%s' not found. "
2105 2162 "Use '%bookmark -l' to see your bookmarks." % ps)
2106 2163 else:
2107 2164 print "Bookmarks not set - use %bookmark <bookmarkname>"
2108 2165 return
2109 2166
2110 2167 # at this point ps should point to the target dir
2111 2168 if ps:
2112 2169 try:
2113 2170 os.chdir(os.path.expanduser(ps))
2114 2171 except OSError:
2115 2172 print sys.exc_info()[1]
2116 2173 else:
2117 2174 self.shell.user_ns['_dh'].append(os.getcwd())
2118 2175 else:
2119 2176 os.chdir(self.home_dir)
2120 2177 self.shell.user_ns['_dh'].append(os.getcwd())
2121 2178 if not 'q' in opts:
2122 2179 print self.shell.user_ns['_dh'][-1]
2123 2180
2124 2181 def magic_dhist(self, parameter_s=''):
2125 2182 """Print your history of visited directories.
2126 2183
2127 2184 %dhist -> print full history\\
2128 2185 %dhist n -> print last n entries only\\
2129 2186 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2130 2187
2131 2188 This history is automatically maintained by the %cd command, and
2132 2189 always available as the global list variable _dh. You can use %cd -<n>
2133 2190 to go to directory number <n>."""
2134 2191
2135 2192 dh = self.shell.user_ns['_dh']
2136 2193 if parameter_s:
2137 2194 try:
2138 2195 args = map(int,parameter_s.split())
2139 2196 except:
2140 2197 self.arg_err(Magic.magic_dhist)
2141 2198 return
2142 2199 if len(args) == 1:
2143 2200 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2144 2201 elif len(args) == 2:
2145 2202 ini,fin = args
2146 2203 else:
2147 2204 self.arg_err(Magic.magic_dhist)
2148 2205 return
2149 2206 else:
2150 2207 ini,fin = 0,len(dh)
2151 2208 nlprint(dh,
2152 2209 header = 'Directory history (kept in _dh)',
2153 2210 start=ini,stop=fin)
2154 2211
2155 2212 def magic_env(self, parameter_s=''):
2156 2213 """List environment variables."""
2157 2214
2158 2215 # environ is an instance of UserDict
2159 2216 return os.environ.data
2160 2217
2161 2218 def magic_pushd(self, parameter_s=''):
2162 2219 """Place the current dir on stack and change directory.
2163 2220
2164 2221 Usage:\\
2165 2222 %pushd ['dirname']
2166 2223
2167 2224 %pushd with no arguments does a %pushd to your home directory.
2168 2225 """
2169 2226 if parameter_s == '': parameter_s = '~'
2170 2227 if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \
2171 2228 os.path.expanduser(self.dir_stack[0]):
2172 2229 try:
2173 2230 self.magic_cd(parameter_s)
2174 2231 self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~'))
2175 2232 self.magic_dirs()
2176 2233 except:
2177 2234 print 'Invalid directory'
2178 2235 else:
2179 2236 print 'You are already there!'
2180 2237
2181 2238 def magic_popd(self, parameter_s=''):
2182 2239 """Change to directory popped off the top of the stack.
2183 2240 """
2184 2241 if len (self.dir_stack) > 1:
2185 2242 self.dir_stack.pop(0)
2186 2243 self.magic_cd(self.dir_stack[0])
2187 2244 print self.dir_stack[0]
2188 2245 else:
2189 2246 print "You can't remove the starting directory from the stack:",\
2190 2247 self.dir_stack
2191 2248
2192 2249 def magic_dirs(self, parameter_s=''):
2193 2250 """Return the current directory stack."""
2194 2251
2195 2252 return self.dir_stack[:]
2196 2253
2197 2254 def magic_sc(self, parameter_s=''):
2198 2255 """Shell capture - execute a shell command and capture its output.
2199 2256
2200 2257 %sc [options] varname=command
2201 2258
2202 2259 IPython will run the given command using commands.getoutput(), and
2203 2260 will then update the user's interactive namespace with a variable
2204 2261 called varname, containing the value of the call. Your command can
2205 2262 contain shell wildcards, pipes, etc.
2206 2263
2207 2264 The '=' sign in the syntax is mandatory, and the variable name you
2208 2265 supply must follow Python's standard conventions for valid names.
2209 2266
2210 2267 Options:
2211 2268
2212 2269 -l: list output. Split the output on newlines into a list before
2213 2270 assigning it to the given variable. By default the output is stored
2214 2271 as a single string.
2215 2272
2216 2273 -v: verbose. Print the contents of the variable.
2217 2274
2218 2275 In most cases you should not need to split as a list, because the
2219 2276 returned value is a special type of string which can automatically
2220 2277 provide its contents either as a list (split on newlines) or as a
2221 2278 space-separated string. These are convenient, respectively, either
2222 2279 for sequential processing or to be passed to a shell command.
2223 2280
2224 2281 For example:
2225 2282
2226 2283 # Capture into variable a
2227 2284 In [9]: sc a=ls *py
2228 2285
2229 2286 # a is a string with embedded newlines
2230 2287 In [10]: a
2231 2288 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2232 2289
2233 2290 # which can be seen as a list:
2234 2291 In [11]: a.l
2235 2292 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2236 2293
2237 2294 # or as a whitespace-separated string:
2238 2295 In [12]: a.s
2239 2296 Out[12]: 'setup.py win32_manual_post_install.py'
2240 2297
2241 2298 # a.s is useful to pass as a single command line:
2242 2299 In [13]: !wc -l $a.s
2243 2300 146 setup.py
2244 2301 130 win32_manual_post_install.py
2245 2302 276 total
2246 2303
2247 2304 # while the list form is useful to loop over:
2248 2305 In [14]: for f in a.l:
2249 2306 ....: !wc -l $f
2250 2307 ....:
2251 2308 146 setup.py
2252 2309 130 win32_manual_post_install.py
2253 2310
2254 2311 Similiarly, the lists returned by the -l option are also special, in
2255 2312 the sense that you can equally invoke the .s attribute on them to
2256 2313 automatically get a whitespace-separated string from their contents:
2257 2314
2258 2315 In [1]: sc -l b=ls *py
2259 2316
2260 2317 In [2]: b
2261 2318 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2262 2319
2263 2320 In [3]: b.s
2264 2321 Out[3]: 'setup.py win32_manual_post_install.py'
2265 2322
2266 2323 In summary, both the lists and strings used for ouptut capture have
2267 2324 the following special attributes:
2268 2325
2269 2326 .l (or .list) : value as list.
2270 2327 .n (or .nlstr): value as newline-separated string.
2271 2328 .s (or .spstr): value as space-separated string.
2272 2329 """
2273 2330
2274 2331 opts,args = self.parse_options(parameter_s,'lv')
2275 2332 # Try to get a variable name and command to run
2276 2333 try:
2277 2334 # the variable name must be obtained from the parse_options
2278 2335 # output, which uses shlex.split to strip options out.
2279 2336 var,_ = args.split('=',1)
2280 2337 var = var.strip()
2281 2338 # But the the command has to be extracted from the original input
2282 2339 # parameter_s, not on what parse_options returns, to avoid the
2283 2340 # quote stripping which shlex.split performs on it.
2284 2341 _,cmd = parameter_s.split('=',1)
2285 2342 except ValueError:
2286 2343 var,cmd = '',''
2287 2344 if not var:
2288 2345 error('you must specify a variable to assign the command to.')
2289 2346 return
2290 2347 # If all looks ok, proceed
2291 2348 out,err = self.shell.getoutputerror(cmd)
2292 2349 if err:
2293 2350 print >> Term.cerr,err
2294 2351 if opts.has_key('l'):
2295 2352 out = SList(out.split('\n'))
2296 2353 else:
2297 2354 out = LSString(out)
2298 2355 if opts.has_key('v'):
2299 2356 print '%s ==\n%s' % (var,pformat(out))
2300 2357 self.shell.user_ns.update({var:out})
2301 2358
2302 2359 def magic_sx(self, parameter_s=''):
2303 2360 """Shell execute - run a shell command and capture its output.
2304 2361
2305 2362 %sx command
2306 2363
2307 2364 IPython will run the given command using commands.getoutput(), and
2308 2365 return the result formatted as a list (split on '\\n'). Since the
2309 2366 output is _returned_, it will be stored in ipython's regular output
2310 2367 cache Out[N] and in the '_N' automatic variables.
2311 2368
2312 2369 Notes:
2313 2370
2314 2371 1) If an input line begins with '!!', then %sx is automatically
2315 2372 invoked. That is, while:
2316 2373 !ls
2317 2374 causes ipython to simply issue system('ls'), typing
2318 2375 !!ls
2319 2376 is a shorthand equivalent to:
2320 2377 %sx ls
2321 2378
2322 2379 2) %sx differs from %sc in that %sx automatically splits into a list,
2323 2380 like '%sc -l'. The reason for this is to make it as easy as possible
2324 2381 to process line-oriented shell output via further python commands.
2325 2382 %sc is meant to provide much finer control, but requires more
2326 2383 typing.
2327 2384
2328 2385 3) Just like %sc -l, this is a list with special attributes:
2329 2386
2330 2387 .l (or .list) : value as list.
2331 2388 .n (or .nlstr): value as newline-separated string.
2332 2389 .s (or .spstr): value as whitespace-separated string.
2333 2390
2334 2391 This is very useful when trying to use such lists as arguments to
2335 2392 system commands."""
2336 2393
2337 2394 if parameter_s:
2338 2395 out,err = self.shell.getoutputerror(parameter_s)
2339 2396 if err:
2340 2397 print >> Term.cerr,err
2341 2398 return SList(out.split('\n'))
2342 2399
2343 2400 def magic_bg(self, parameter_s=''):
2344 2401 """Run a job in the background, in a separate thread.
2345 2402
2346 2403 For example,
2347 2404
2348 2405 %bg myfunc(x,y,z=1)
2349 2406
2350 2407 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2351 2408 execution starts, a message will be printed indicating the job
2352 2409 number. If your job number is 5, you can use
2353 2410
2354 2411 myvar = jobs.result(5) or myvar = jobs[5].result
2355 2412
2356 2413 to assign this result to variable 'myvar'.
2357 2414
2358 2415 IPython has a job manager, accessible via the 'jobs' object. You can
2359 2416 type jobs? to get more information about it, and use jobs.<TAB> to see
2360 2417 its attributes. All attributes not starting with an underscore are
2361 2418 meant for public use.
2362 2419
2363 2420 In particular, look at the jobs.new() method, which is used to create
2364 2421 new jobs. This magic %bg function is just a convenience wrapper
2365 2422 around jobs.new(), for expression-based jobs. If you want to create a
2366 2423 new job with an explicit function object and arguments, you must call
2367 2424 jobs.new() directly.
2368 2425
2369 2426 The jobs.new docstring also describes in detail several important
2370 2427 caveats associated with a thread-based model for background job
2371 2428 execution. Type jobs.new? for details.
2372 2429
2373 2430 You can check the status of all jobs with jobs.status().
2374 2431
2375 2432 The jobs variable is set by IPython into the Python builtin namespace.
2376 2433 If you ever declare a variable named 'jobs', you will shadow this
2377 2434 name. You can either delete your global jobs variable to regain
2378 2435 access to the job manager, or make a new name and assign it manually
2379 2436 to the manager (stored in IPython's namespace). For example, to
2380 2437 assign the job manager to the Jobs name, use:
2381 2438
2382 2439 Jobs = __builtins__.jobs"""
2383 2440
2384 2441 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2385 2442
2386 2443 def magic_bookmark(self, parameter_s=''):
2387 2444 """Manage IPython's bookmark system.
2388 2445
2389 2446 %bookmark <name> - set bookmark to current dir
2390 2447 %bookmark <name> <dir> - set bookmark to <dir>
2391 2448 %bookmark -l - list all bookmarks
2392 2449 %bookmark -d <name> - remove bookmark
2393 2450 %bookmark -r - remove all bookmarks
2394 2451
2395 2452 You can later on access a bookmarked folder with:
2396 2453 %cd -b <name>
2397 2454 or simply '%cd <name>' if there is no directory called <name> AND
2398 2455 there is such a bookmark defined.
2399 2456
2400 2457 Your bookmarks persist through IPython sessions, but they are
2401 2458 associated with each profile."""
2402 2459
2403 2460 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2404 2461 if len(args) > 2:
2405 2462 error('You can only give at most two arguments')
2406 2463 return
2407 2464
2408 2465 bkms = self.shell.persist.get('bookmarks',{})
2409 2466
2410 2467 if opts.has_key('d'):
2411 2468 try:
2412 2469 todel = args[0]
2413 2470 except IndexError:
2414 2471 error('You must provide a bookmark to delete')
2415 2472 else:
2416 2473 try:
2417 2474 del bkms[todel]
2418 2475 except:
2419 2476 error("Can't delete bookmark '%s'" % todel)
2420 2477 elif opts.has_key('r'):
2421 2478 bkms = {}
2422 2479 elif opts.has_key('l'):
2423 2480 bks = bkms.keys()
2424 2481 bks.sort()
2425 2482 if bks:
2426 2483 size = max(map(len,bks))
2427 2484 else:
2428 2485 size = 0
2429 2486 fmt = '%-'+str(size)+'s -> %s'
2430 2487 print 'Current bookmarks:'
2431 2488 for bk in bks:
2432 2489 print fmt % (bk,bkms[bk])
2433 2490 else:
2434 2491 if not args:
2435 2492 error("You must specify the bookmark name")
2436 2493 elif len(args)==1:
2437 2494 bkms[args[0]] = os.getcwd()
2438 2495 elif len(args)==2:
2439 2496 bkms[args[0]] = args[1]
2440 2497 self.persist['bookmarks'] = bkms
2441 2498
2442 2499 def magic_pycat(self, parameter_s=''):
2443 2500 """Show a syntax-highlighted file through a pager.
2444 2501
2445 2502 This magic is similar to the cat utility, but it will assume the file
2446 2503 to be Python source and will show it with syntax highlighting. """
2447 2504
2448 2505 filename = get_py_filename(parameter_s)
2449 2506 page(self.shell.colorize(file_read(filename)),
2450 2507 screen_lines=self.shell.rc.screen_length)
2451 2508
2452 2509 # end Magic
@@ -1,398 +1,442 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 575 2005-04-08 14:16:44Z fperez $
9 $Id: OInspect.py 919 2005-10-15 07:57:05Z 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 inspect,linecache,types,StringIO,string
27 27
28 28 # IPython's own
29 from IPython import PyColorize
29 30 from IPython.Itpl import itpl
31 from IPython.wildcard import choose_namespaces,list_namespace
30 32 from IPython.genutils import page,indent,Term
31 from IPython import PyColorize
32 33 from IPython.ColorANSI import *
33 34
34 35 #****************************************************************************
35 36 # Builtin color schemes
36 37
37 38 Colors = TermColors # just a shorthand
38 39
39 40 # Build a few color schemes
40 41 NoColor = ColorScheme(
41 42 'NoColor',{
42 43 'header' : Colors.NoColor,
43 44 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
44 45 } )
45 46
46 47 LinuxColors = ColorScheme(
47 48 'Linux',{
48 49 'header' : Colors.LightRed,
49 50 'normal' : Colors.Normal # color off (usu. Colors.Normal)
50 51 } )
51 52
52 53 LightBGColors = ColorScheme(
53 54 'LightBG',{
54 55 'header' : Colors.Red,
55 56 'normal' : Colors.Normal # color off (usu. Colors.Normal)
56 57 } )
57 58
58 59 # Build table of color schemes (needed by the parser)
59 60 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
60 61 'Linux')
61 62
62 63 #****************************************************************************
63 64 # Auxiliary functions
64 65 def getdoc(obj):
65 66 """Stable wrapper around inspect.getdoc.
66 67
67 68 This can't crash because of attribute problems.
68 69
69 70 It also attempts to call a getdoc() method on the given object. This
70 71 allows objects which provide their docstrings via non-standard mechanisms
71 72 (like Pyro proxies) to still be inspected by ipython's ? system."""
72 73
73 74 ds = None # default return value
74 75 try:
75 76 ds = inspect.getdoc(obj)
76 77 except:
77 78 # Harden against an inspect failure, which can occur with
78 79 # SWIG-wrapped extensions.
79 80 pass
80 81 # Allow objects to offer customized documentation via a getdoc method:
81 82 try:
82 83 ds2 = obj.getdoc()
83 84 except:
84 85 pass
85 86 else:
86 87 # if we get extra info, we add it to the normal docstring.
87 88 if ds is None:
88 89 ds = ds2
89 90 else:
90 91 ds = '%s\n%s' % (ds,ds2)
91 92 return ds
92 93
93 94 #****************************************************************************
94 95 # Class definitions
95 96
96 97 class myStringIO(StringIO.StringIO):
97 98 """Adds a writeln method to normal StringIO."""
98 99 def writeln(self,*arg,**kw):
99 100 """Does a write() and then a write('\n')"""
100 101 self.write(*arg,**kw)
101 102 self.write('\n')
102 103
103 104 class Inspector:
104 105 def __init__(self,color_table,code_color_table,scheme):
105 106 self.color_table = color_table
106 107 self.parser = PyColorize.Parser(code_color_table,out='str')
107 108 self.format = self.parser.format
108 109 self.set_active_scheme(scheme)
109 110
110 111 def __getargspec(self,obj):
111 112 """Get the names and default values of a function's arguments.
112 113
113 114 A tuple of four things is returned: (args, varargs, varkw, defaults).
114 115 'args' is a list of the argument names (it may contain nested lists).
115 116 'varargs' and 'varkw' are the names of the * and ** arguments or None.
116 117 'defaults' is an n-tuple of the default values of the last n arguments.
117 118
118 119 Modified version of inspect.getargspec from the Python Standard
119 120 Library."""
120 121
121 122 if inspect.isfunction(obj):
122 123 func_obj = obj
123 124 elif inspect.ismethod(obj):
124 125 func_obj = obj.im_func
125 126 else:
126 127 raise TypeError, 'arg is not a Python function'
127 128 args, varargs, varkw = inspect.getargs(func_obj.func_code)
128 129 return args, varargs, varkw, func_obj.func_defaults
129 130
130 131 def __getdef(self,obj,oname=''):
131 132 """Return the definition header for any callable object.
132 133
133 134 If any exception is generated, None is returned instead and the
134 135 exception is suppressed."""
135 136
136 137 try:
137 138 return oname + inspect.formatargspec(*self.__getargspec(obj))
138 139 except:
139 140 return None
140 141
141 142 def __head(self,h):
142 143 """Return a header string with proper colors."""
143 144 return '%s%s%s' % (self.color_table.active_colors.header,h,
144 145 self.color_table.active_colors.normal)
145 146
146 147 def set_active_scheme(self,scheme):
147 148 self.color_table.set_active_scheme(scheme)
148 149 self.parser.color_table.set_active_scheme(scheme)
149 150
150 151 def noinfo(self,msg,oname):
151 152 """Generic message when no information is found."""
152 153 print 'No %s found' % msg,
153 154 if oname:
154 155 print 'for %s' % oname
155 156 else:
156 157 print
157 158
158 159 def pdef(self,obj,oname=''):
159 160 """Print the definition header for any callable object.
160 161
161 162 If the object is a class, print the constructor information."""
162 163
163 164 if not callable(obj):
164 165 print 'Object is not callable.'
165 166 return
166 167
167 168 header = ''
168 169 if type(obj) is types.ClassType:
169 170 header = self.__head('Class constructor information:\n')
170 171 obj = obj.__init__
171 172 elif type(obj) is types.InstanceType:
172 173 obj = obj.__call__
173 174
174 175 output = self.__getdef(obj,oname)
175 176 if output is None:
176 177 self.noinfo('definition header',oname)
177 178 else:
178 179 print >>Term.cout, header,self.format(output),
179 180
180 181 def pdoc(self,obj,oname='',formatter = None):
181 182 """Print the docstring for any object.
182 183
183 184 Optional:
184 185 -formatter: a function to run the docstring through for specially
185 186 formatted docstrings."""
186 187
187 188 head = self.__head # so that itpl can find it even if private
188 189 ds = getdoc(obj)
189 190 if formatter:
190 191 ds = formatter(ds)
191 192 if type(obj) is types.ClassType:
192 193 init_ds = getdoc(obj.__init__)
193 194 output = itpl('$head("Class Docstring:")\n'
194 195 '$indent(ds)\n'
195 196 '$head("Constructor Docstring"):\n'
196 197 '$indent(init_ds)')
197 198 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
198 199 call_ds = getdoc(obj.__call__)
199 200 if call_ds:
200 201 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
201 202 '$head("Calling Docstring:")\n$indent(call_ds)')
202 203 else:
203 204 output = ds
204 205 else:
205 206 output = ds
206 207 if output is None:
207 208 self.noinfo('documentation',oname)
208 209 return
209 210 page(output)
210 211
211 212 def psource(self,obj,oname=''):
212 213 """Print the source code for an object."""
213 214
214 215 # Flush the source cache because inspect can return out-of-date source
215 216 linecache.checkcache()
216 217 try:
217 218 src = inspect.getsource(obj)
218 219 except:
219 220 self.noinfo('source',oname)
220 221 else:
221 222 page(self.format(src))
222 223
223 224 def pfile(self,obj,oname=''):
224 225 """Show the whole file where an object was defined."""
225 226 try:
226 227 sourcelines,lineno = inspect.getsourcelines(obj)
227 228 except:
228 229 self.noinfo('file',oname)
229 230 else:
230 231 # run contents of file through pager starting at line
231 232 # where the object is defined
232 233 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
233 234
234 235 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
235 236 """Show detailed information about an object.
236 237
237 238 Optional arguments:
238 239
239 240 - oname: name of the variable pointing to the object.
240 241
241 242 - formatter: special formatter for docstrings (see pdoc)
242 243
243 244 - info: a structure with some information fields which may have been
244 245 precomputed already.
245 246
246 247 - detail_level: if set to 1, more information is given.
247 248 """
248 249
249 250 obj_type = type(obj)
250 251
251 252 header = self.__head
252 253 if info is None:
253 254 ismagic = 0
254 255 isalias = 0
255 256 ospace = ''
256 257 else:
257 258 ismagic = info.ismagic
258 259 isalias = info.isalias
259 260 ospace = info.namespace
260 261 # Get docstring, special-casing aliases:
261 262 if isalias:
262 263 ds = "Alias to the system command:\n %s" % obj[1]
263 264 else:
264 265 ds = getdoc(obj)
265 266 if formatter is not None:
266 267 ds = formatter(ds)
267 268
268 269 # store output in a list which gets joined with \n at the end.
269 270 out = myStringIO()
270 271
271 272 string_max = 200 # max size of strings to show (snipped if longer)
272 273 shalf = int((string_max -5)/2)
273 274
274 275 if ismagic:
275 276 obj_type_name = 'Magic function'
276 277 elif isalias:
277 278 obj_type_name = 'System alias'
278 279 else:
279 280 obj_type_name = obj_type.__name__
280 281 out.writeln(header('Type:\t\t')+obj_type_name)
281 282
282 283 try:
283 284 bclass = obj.__class__
284 285 out.writeln(header('Base Class:\t')+str(bclass))
285 286 except: pass
286 287
287 288 # String form, but snip if too long in ? form (full in ??)
288 289 try:
289 290 ostr = str(obj)
290 291 str_head = 'String Form:'
291 292 if not detail_level and len(ostr)>string_max:
292 293 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
293 294 ostr = ("\n" + " " * len(str_head.expandtabs())).\
294 295 join(map(string.strip,ostr.split("\n")))
295 296 if ostr.find('\n') > -1:
296 297 # Print multi-line strings starting at the next line.
297 298 str_sep = '\n'
298 299 else:
299 300 str_sep = '\t'
300 301 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
301 302 except:
302 303 pass
303 304
304 305 if ospace:
305 306 out.writeln(header('Namespace:\t')+ospace)
306 307
307 308 # Length (for strings and lists)
308 309 try:
309 310 length = str(len(obj))
310 311 out.writeln(header('Length:\t\t')+length)
311 312 except: pass
312 313
313 314 # Filename where object was defined
314 315 try:
315 316 file = inspect.getabsfile(obj)
316 317 if file.endswith('<string>'):
317 318 file = 'Dynamically generated function. No source code available.'
318 319 out.writeln(header('File:\t\t')+file)
319 320 except: pass
320 321
321 322 # reconstruct the function definition and print it:
322 323 defln = self.__getdef(obj,oname)
323 324 if defln:
324 325 out.write(header('Definition:\t')+self.format(defln))
325 326
326 327 # Docstrings only in detail 0 mode, since source contains them (we
327 328 # avoid repetitions). If source fails, we add them back, see below.
328 329 if ds and detail_level == 0:
329 330 out.writeln(header('Docstring:\n') + indent(ds))
330 331
331 332 # Original source code for any callable
332 333 if detail_level:
333 334 # Flush the source cache because inspect can return out-of-date source
334 335 linecache.checkcache()
335 336 try:
336 337 source = self.format(inspect.getsource(obj))
337 338 out.write(header('Source:\n')+source.rstrip())
338 339 except:
339 340 if ds:
340 341 out.writeln(header('Docstring:\n') + indent(ds))
341 342
342 343 # Constructor docstring for classes
343 344 if obj_type is types.ClassType:
344 345 # reconstruct the function definition and print it:
345 346 try:
346 347 obj_init = obj.__init__
347 348 except AttributeError:
348 349 init_def = init_ds = None
349 350 else:
350 351 init_def = self.__getdef(obj_init,oname)
351 352 init_ds = getdoc(obj_init)
352 353
353 354 if init_def or init_ds:
354 355 out.writeln(header('\nConstructor information:'))
355 356 if init_def:
356 357 out.write(header('Definition:\t')+ self.format(init_def))
357 358 if init_ds:
358 359 out.writeln(header('Docstring:\n') + indent(init_ds))
359 360 # and class docstring for instances:
360 361 elif obj_type is types.InstanceType:
361 362
362 363 # First, check whether the instance docstring is identical to the
363 364 # class one, and print it separately if they don't coincide. In
364 365 # most cases they will, but it's nice to print all the info for
365 366 # objects which use instance-customized docstrings.
366 367 if ds:
367 368 class_ds = getdoc(obj.__class__)
368 369 if class_ds and ds != class_ds:
369 370 out.writeln(header('Class Docstring:\n') +
370 371 indent(class_ds))
371 372
372 373 # Next, try to show constructor docstrings
373 374 try:
374 375 init_ds = getdoc(obj.__init__)
375 376 except AttributeError:
376 377 init_ds = None
377 378 if init_ds:
378 379 out.writeln(header('Constructor Docstring:\n') +
379 380 indent(init_ds))
380 381
381 382 # Call form docstring for callable instances
382 383 if hasattr(obj,'__call__'):
383 384 out.writeln(header('Callable:\t')+'Yes')
384 385 call_def = self.__getdef(obj.__call__,oname)
385 386 if call_def is None:
386 387 out.write(header('Call def:\t')+
387 388 'Calling definition not available.')
388 389 else:
389 390 out.write(header('Call def:\t')+self.format(call_def))
390 391 call_ds = getdoc(obj.__call__)
391 392 if call_ds:
392 393 out.writeln(header('Call docstring:\n') + indent(call_ds))
393 394
394 395 # Finally send to printer/pager
395 396 output = out.getvalue()
396 397 if output:
397 398 page(output)
398 399 # end pinfo
400
401 def psearch(self,oname='',formatter = None,shell=None):
402 """Search namespaces with wildcards for objects.
403
404 Optional arguments:
405
406 - oname: rest of the commandline containging pattern and options
407
408 - formatter: Not used
409
410 - shell: The shell object from the Magic class. Needed to
411 access the namespaces
412
413 """
414 option_list=["-c","-a"]
415 import pdb
416 # pdb.set_trace()
417 cmds=oname.split()
418 filter=""
419 type_pattern="all"
420 ns_cmds=[]
421 options=[x for x in cmds if x in option_list]
422 ignorecase="-c" not in options
423 showhidden="-a" in options
424 ns_cmds=[x for x in cmds if x[0] in "-+" and x not in option_list]
425 cmds=[x for x in cmds if x[0] not in "-+"]
426 if len(cmds)>2: #assume we want to choose name spaces.
427 #Rather poor design forces the use of a typepattern in order to choose name spaces
428 cmds=cmds[:2]
429 if len(cmds)==2:
430 filter,type_pattern=cmds
431 elif len(cmds)==1:
432 filter=cmds[0].strip()
433
434 do_list=choose_namespaces(shell,ns_cmds)
435
436 search_result=[]
437 for ns in do_list:
438 tmp_res=list(list_namespace(ns,type_pattern,filter,ignorecase=ignorecase,showhidden=showhidden))
439 search_result.extend(tmp_res)
440 search_result.sort()
441
442 page("\n".join(search_result))
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
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