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