##// END OF EJS Templates
Pdb calling, pickle (under certain circumstances, connected with %run) and...
fperez -
Show More

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

@@ -1,221 +1,228 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Logger class for IPython's logging facilities.
4 4
5 $Id: Logger.py 974 2005-12-29 19:48:33Z fperez $
5 $Id: Logger.py 984 2005-12-31 08:40:31Z fperez $
6 6 """
7 7
8 8 #*****************************************************************************
9 9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
10 10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 #****************************************************************************
17 17 # Modules and globals
18 18
19 19 from IPython import Release
20 20 __author__ = '%s <%s>\n%s <%s>' % \
21 21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22 22 __license__ = Release.license
23 23
24 24 # Python standard modules
25 25 import glob
26 26 import os
27 27 import time
28 28
29 29 #****************************************************************************
30 30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
31 31 # ipython and does input cache management. Finish cleanup later...
32 32
33 33 class Logger(object):
34 34 """A Logfile class with different policies for file creation"""
35 35
36 36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
37 37
38 38 self._i00,self._i,self._ii,self._iii = '','','',''
39 39
40 40 # this is the full ipython instance, we need some attributes from it
41 41 # which won't exist until later. What a mess, clean up later...
42 42 self.shell = shell
43 43
44 44 self.logfname = logfname
45 45 self.loghead = loghead
46 46 self.logmode = logmode
47 47 self.logfile = None
48 48
49 49 # whether to also log output
50 50 self.log_output = False
51 51
52 52 # whether to put timestamps before each log entry
53 53 self.timestamp = False
54 54
55 55 # activity control flags
56 56 self.log_active = False
57 57
58 58 # logmode is a validated property
59 59 def _set_mode(self,mode):
60 60 if mode not in ['append','backup','global','over','rotate']:
61 61 raise ValueError,'invalid log mode %s given' % mode
62 62 self._logmode = mode
63 63
64 64 def _get_mode(self):
65 65 return self._logmode
66 66
67 67 logmode = property(_get_mode,_set_mode)
68 68
69 69 def logstart(self,logfname=None,loghead=None,logmode=None,
70 70 log_output=False,timestamp=False):
71 71 """Generate a new log-file with a default header.
72 72
73 73 Raises RuntimeError if the log has already been started"""
74 74
75 75 if self.logfile is not None:
76 76 raise RuntimeError('Log file is already active: %s' %
77 77 self.logfname)
78 78
79 79 self.log_active = True
80 80
81 81 # The three parameters can override constructor defaults
82 82 if logfname: self.logfname = logfname
83 83 if loghead: self.loghead = loghead
84 84 if logmode: self.logmode = logmode
85 85 self.timestamp = timestamp
86 86 self.log_output = log_output
87 87
88 88 # init depending on the log mode requested
89 89 isfile = os.path.isfile
90 90 logmode = self.logmode
91 91
92 92 if logmode == 'append':
93 93 self.logfile = open(self.logfname,'a')
94 94
95 95 elif logmode == 'backup':
96 96 if isfile(self.logfname):
97 97 backup_logname = self.logfname+'~'
98 98 # Manually remove any old backup, since os.rename may fail
99 99 # under Windows.
100 100 if isfile(backup_logname):
101 101 os.remove(backup_logname)
102 102 os.rename(self.logfname,backup_logname)
103 103 self.logfile = open(self.logfname,'w')
104 104
105 105 elif logmode == 'global':
106 106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
107 107 self.logfile = open(self.logfname, 'a')
108 108
109 109 elif logmode == 'over':
110 110 if isfile(self.logfname):
111 111 os.remove(self.logfname)
112 112 self.logfile = open(self.logfname,'w')
113 113
114 114 elif logmode == 'rotate':
115 115 if isfile(self.logfname):
116 116 if isfile(self.logfname+'.001~'):
117 117 old = glob.glob(self.logfname+'.*~')
118 118 old.sort()
119 119 old.reverse()
120 120 for f in old:
121 121 root, ext = os.path.splitext(f)
122 122 num = int(ext[1:-1])+1
123 123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
124 124 os.rename(self.logfname, self.logfname+'.001~')
125 125 self.logfile = open(self.logfname,'w')
126 126
127 127 if logmode != 'append':
128 128 self.logfile.write(self.loghead)
129 129
130 130 self.logfile.flush()
131 131
132 132 def switch_log(self,val):
133 133 """Switch logging on/off. val should be ONLY a boolean."""
134 134
135 135 if val not in [False,True,0,1]:
136 136 raise ValueError, \
137 137 'Call switch_log ONLY with a boolean argument, not with:',val
138 138
139 139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
140 140
141 141 if self.logfile is None:
142 142 print """
143 143 Logging hasn't been started yet (use logstart for that).
144 144
145 145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
146 146 which already exists. But you must first start the logging process with
147 147 %logstart (optionally giving a logfile name)."""
148 148
149 149 else:
150 150 if self.log_active == val:
151 151 print 'Logging is already',label[val]
152 152 else:
153 153 print 'Switching logging',label[val]
154 154 self.log_active = not self.log_active
155 155 self.log_active_out = self.log_active
156 156
157 157 def logstate(self):
158 158 """Print a status message about the logger."""
159 159 if self.logfile is None:
160 160 print 'Logging has not been activated.'
161 161 else:
162 162 state = self.log_active and 'active' or 'temporarily suspended'
163 163 print 'Filename :',self.logfname
164 164 print 'Mode :',self.logmode
165 165 print 'Output logging :',self.log_output
166 166 print 'Timestamping :',self.timestamp
167 167 print 'State :',state
168 168
169 169 def log(self, line,continuation=None):
170 170 """Write the line to a log and create input cache variables _i*."""
171 171
172 172 # update the auto _i tables
173 173 #print '***logging line',line # dbg
174 174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
175 175 input_hist = self.shell.user_ns['_ih']
176 176 if not continuation and line:
177 177 self._iii = self._ii
178 178 self._ii = self._i
179 179 self._i = self._i00
180 180 # put back the final \n of every input line
181 181 self._i00 = line+'\n'
182 182 #print 'Logging input:<%s>' % line # dbg
183 183 input_hist.append(self._i00)
184 #print '---[%s]' % (len(input_hist)-1,) # dbg
184 185
185 186 # hackish access to top-level namespace to create _i1,_i2... dynamically
186 187 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
187 188 if self.shell.outputcache.do_full_cache:
188 189 in_num = self.shell.outputcache.prompt_count
189 190 # add blank lines if the input cache fell out of sync. This can
190 191 # happen for embedded instances which get killed via C-D and then
191 192 # get resumed.
192 193 while in_num >= len(input_hist):
193 194 input_hist.append('\n')
195 # but if the opposite is true (a macro can produce multiple inputs
196 # with no output display called), then bring the output counter in
197 # sync:
198 last_num = len(input_hist)-1
199 if in_num != last_num:
200 in_num = self.shell.outputcache.prompt_count = last_num
194 201 new_i = '_i%s' % in_num
195 202 if continuation:
196 203 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
197 204 input_hist[in_num] = self._i00
198 205 to_main[new_i] = self._i00
199 206 self.shell.user_ns.update(to_main)
200 207 self.log_write(line)
201 208
202 209 def log_write(self,data,kind='input'):
203 210 """Write data to the log file, if active"""
204 211
205 212 if self.log_active and data:
206 213 write = self.logfile.write
207 214 if kind=='input':
208 215 if self.timestamp:
209 216 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
210 217 time.localtime()))
211 218 write('%s\n' % data)
212 219 elif kind=='output' and self.log_output:
213 220 odata = '\n'.join(['#[Out]# %s' % s
214 221 for s in data.split('\n')])
215 222 write('%s\n' % odata)
216 223 self.logfile.flush()
217 224
218 225 def close_log(self):
219 226 self.logfile.close()
220 227 self.logfile = None
221 228 self.logfname = ''
@@ -1,2672 +1,2677 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 975 2005-12-29 23:50:22Z fperez $"""
4 $Id: Magic.py 984 2005-12-31 08:40:31Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 from cStringIO import StringIO
35 35 from getopt import getopt
36 36 from pprint import pprint, pformat
37 37
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 from IPython import Debugger, OInspect, wildcard
46 46 from IPython.FakeModule import FakeModule
47 47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 48 from IPython.PyColorize import Parser
49 49 from IPython.Struct import Struct
50 50 from IPython.macro import Macro
51 51 from IPython.genutils import *
52 52
53 53 #***************************************************************************
54 54 # Utility functions
55 55 def on_off(tag):
56 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
57 57 return ['OFF','ON'][tag]
58 58
59 59
60 60 #***************************************************************************
61 61 # Main class implementing Magic functionality
62 62 class Magic:
63 63 """Magic functions for InteractiveShell.
64 64
65 65 Shell functions which can be reached as %function_name. All magic
66 66 functions should accept a string, which they can parse for their own
67 67 needs. This can make some functions easier to type, eg `%cd ../`
68 68 vs. `%cd("../")`
69 69
70 70 ALL definitions MUST begin with the prefix magic_. The user won't need it
71 71 at the command line, but it is is needed in the definition. """
72 72
73 73 # class globals
74 74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
75 75 'Automagic is ON, % prefix NOT needed for magic functions.']
76 76
77 77 #......................................................................
78 78 # some utility functions
79 79
80 80 def __init__(self,shell):
81 81
82 82 self.options_table = {}
83 83 if profile is None:
84 84 self.magic_prun = self.profile_missing_notice
85 85 self.shell = shell
86 86
87 87 def profile_missing_notice(self, *args, **kwargs):
88 88 error("""\
89 89 The profile module could not be found. If you are a Debian user,
90 90 it has been removed from the standard Debian package because of its non-free
91 91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
92 92
93 93 def default_option(self,fn,optstr):
94 94 """Make an entry in the options_table for fn, with value optstr"""
95 95
96 96 if fn not in self.lsmagic():
97 97 error("%s is not a magic function" % fn)
98 98 self.options_table[fn] = optstr
99 99
100 100 def lsmagic(self):
101 101 """Return a list of currently available magic functions.
102 102
103 103 Gives a list of the bare names after mangling (['ls','cd', ...], not
104 104 ['magic_ls','magic_cd',...]"""
105 105
106 106 # FIXME. This needs a cleanup, in the way the magics list is built.
107 107
108 108 # magics in class definition
109 109 class_magic = lambda fn: fn.startswith('magic_') and \
110 110 callable(Magic.__dict__[fn])
111 111 # in instance namespace (run-time user additions)
112 112 inst_magic = lambda fn: fn.startswith('magic_') and \
113 113 callable(self.__dict__[fn])
114 114 # and bound magics by user (so they can access self):
115 115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
116 116 callable(self.__class__.__dict__[fn])
117 117 magics = filter(class_magic,Magic.__dict__.keys()) + \
118 118 filter(inst_magic,self.__dict__.keys()) + \
119 119 filter(inst_bound_magic,self.__class__.__dict__.keys())
120 120 out = []
121 121 for fn in magics:
122 122 out.append(fn.replace('magic_','',1))
123 123 out.sort()
124 124 return out
125 125
126 126 def extract_input_slices(self,slices):
127 127 """Return as a string a set of input history slices.
128 128
129 129 The set of slices is given as a list of strings (like ['1','4:8','9'],
130 130 since this function is for use by magic functions which get their
131 131 arguments as strings."""
132 132
133 133 cmds = []
134 134 for chunk in slices:
135 135 if ':' in chunk:
136 136 ini,fin = map(int,chunk.split(':'))
137 137 else:
138 138 ini = int(chunk)
139 139 fin = ini+1
140 140 cmds.append(self.shell.input_hist[ini:fin])
141 141 return cmds
142 142
143 143 def _ofind(self,oname):
144 144 """Find an object in the available namespaces.
145 145
146 146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
147 147
148 148 Has special code to detect magic functions.
149 149 """
150 150
151 151 oname = oname.strip()
152 152
153 153 # Namespaces to search in:
154 154 user_ns = self.shell.user_ns
155 155 internal_ns = self.shell.internal_ns
156 156 builtin_ns = __builtin__.__dict__
157 157 alias_ns = self.shell.alias_table
158 158
159 159 # Put them in a list. The order is important so that we find things in
160 160 # the same order that Python finds them.
161 161 namespaces = [ ('Interactive',user_ns),
162 162 ('IPython internal',internal_ns),
163 163 ('Python builtin',builtin_ns),
164 164 ('Alias',alias_ns),
165 165 ]
166 166
167 167 # initialize results to 'null'
168 168 found = 0; obj = None; ospace = None; ds = None;
169 169 ismagic = 0; isalias = 0
170 170
171 171 # Look for the given name by splitting it in parts. If the head is
172 172 # found, then we look for all the remaining parts as members, and only
173 173 # declare success if we can find them all.
174 174 oname_parts = oname.split('.')
175 175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
176 176 for nsname,ns in namespaces:
177 177 try:
178 178 obj = ns[oname_head]
179 179 except KeyError:
180 180 continue
181 181 else:
182 182 for part in oname_rest:
183 183 try:
184 184 obj = getattr(obj,part)
185 185 except:
186 186 # Blanket except b/c some badly implemented objects
187 187 # allow __getattr__ to raise exceptions other than
188 188 # AttributeError, which then crashes IPython.
189 189 break
190 190 else:
191 191 # If we finish the for loop (no break), we got all members
192 192 found = 1
193 193 ospace = nsname
194 194 if ns == alias_ns:
195 195 isalias = 1
196 196 break # namespace loop
197 197
198 198 # Try to see if it's magic
199 199 if not found:
200 200 if oname.startswith(self.shell.ESC_MAGIC):
201 201 oname = oname[1:]
202 202 obj = getattr(self,'magic_'+oname,None)
203 203 if obj is not None:
204 204 found = 1
205 205 ospace = 'IPython internal'
206 206 ismagic = 1
207 207
208 208 # Last try: special-case some literals like '', [], {}, etc:
209 209 if not found and oname_head in ["''",'""','[]','{}','()']:
210 210 obj = eval(oname_head)
211 211 found = 1
212 212 ospace = 'Interactive'
213 213
214 214 return {'found':found, 'obj':obj, 'namespace':ospace,
215 215 'ismagic':ismagic, 'isalias':isalias}
216 216
217 217 def arg_err(self,func):
218 218 """Print docstring if incorrect arguments were passed"""
219 219 print 'Error in arguments:'
220 220 print OInspect.getdoc(func)
221 221
222 222 def format_latex(self,strng):
223 223 """Format a string for latex inclusion."""
224 224
225 225 # Characters that need to be escaped for latex:
226 226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
227 227 # Magic command names as headers:
228 228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
229 229 re.MULTILINE)
230 230 # Magic commands
231 231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
232 232 re.MULTILINE)
233 233 # Paragraph continue
234 234 par_re = re.compile(r'\\$',re.MULTILINE)
235 235
236 236 # The "\n" symbol
237 237 newline_re = re.compile(r'\\n')
238 238
239 239 # Now build the string for output:
240 240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
241 241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
242 242 strng = par_re.sub(r'\\\\',strng)
243 243 strng = escape_re.sub(r'\\\1',strng)
244 244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
245 245 return strng
246 246
247 247 def format_screen(self,strng):
248 248 """Format a string for screen printing.
249 249
250 250 This removes some latex-type format codes."""
251 251 # Paragraph continue
252 252 par_re = re.compile(r'\\$',re.MULTILINE)
253 253 strng = par_re.sub('',strng)
254 254 return strng
255 255
256 256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
257 257 """Parse options passed to an argument string.
258 258
259 259 The interface is similar to that of getopt(), but it returns back a
260 260 Struct with the options as keys and the stripped argument string still
261 261 as a string.
262 262
263 263 arg_str is quoted as a true sys.argv vector by using shlex.split.
264 264 This allows us to easily expand variables, glob files, quote
265 265 arguments, etc.
266 266
267 267 Options:
268 268 -mode: default 'string'. If given as 'list', the argument string is
269 269 returned as a list (split on whitespace) instead of a string.
270 270
271 271 -list_all: put all option values in lists. Normally only options
272 272 appearing more than once are put in a list."""
273 273
274 274 # inject default options at the beginning of the input line
275 275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
276 276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
277 277
278 278 mode = kw.get('mode','string')
279 279 if mode not in ['string','list']:
280 280 raise ValueError,'incorrect mode given: %s' % mode
281 281 # Get options
282 282 list_all = kw.get('list_all',0)
283 283
284 284 # Check if we have more than one argument to warrant extra processing:
285 285 odict = {} # Dictionary with options
286 286 args = arg_str.split()
287 287 if len(args) >= 1:
288 288 # If the list of inputs only has 0 or 1 thing in it, there's no
289 289 # need to look for options
290 290 argv = shlex_split(arg_str)
291 291 # Do regular option processing
292 292 opts,args = getopt(argv,opt_str,*long_opts)
293 293 for o,a in opts:
294 294 if o.startswith('--'):
295 295 o = o[2:]
296 296 else:
297 297 o = o[1:]
298 298 try:
299 299 odict[o].append(a)
300 300 except AttributeError:
301 301 odict[o] = [odict[o],a]
302 302 except KeyError:
303 303 if list_all:
304 304 odict[o] = [a]
305 305 else:
306 306 odict[o] = a
307 307
308 308 # Prepare opts,args for return
309 309 opts = Struct(odict)
310 310 if mode == 'string':
311 311 args = ' '.join(args)
312 312
313 313 return opts,args
314 314
315 315 #......................................................................
316 316 # And now the actual magic functions
317 317
318 318 # Functions for IPython shell work (vars,funcs, config, etc)
319 319 def magic_lsmagic(self, parameter_s = ''):
320 320 """List currently available magic functions."""
321 321 mesc = self.shell.ESC_MAGIC
322 322 print 'Available magic functions:\n'+mesc+\
323 323 (' '+mesc).join(self.lsmagic())
324 324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
325 325 return None
326 326
327 327 def magic_magic(self, parameter_s = ''):
328 328 """Print information about the magic function system."""
329 329
330 330 mode = ''
331 331 try:
332 332 if parameter_s.split()[0] == '-latex':
333 333 mode = 'latex'
334 334 except:
335 335 pass
336 336
337 337 magic_docs = []
338 338 for fname in self.lsmagic():
339 339 mname = 'magic_' + fname
340 340 for space in (Magic,self,self.__class__):
341 341 try:
342 342 fn = space.__dict__[mname]
343 343 except KeyError:
344 344 pass
345 345 else:
346 346 break
347 347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
348 348 fname,fn.__doc__))
349 349 magic_docs = ''.join(magic_docs)
350 350
351 351 if mode == 'latex':
352 352 print self.format_latex(magic_docs)
353 353 return
354 354 else:
355 355 magic_docs = self.format_screen(magic_docs)
356 356
357 357 outmsg = """
358 358 IPython's 'magic' functions
359 359 ===========================
360 360
361 361 The magic function system provides a series of functions which allow you to
362 362 control the behavior of IPython itself, plus a lot of system-type
363 363 features. All these functions are prefixed with a % character, but parameters
364 364 are given without parentheses or quotes.
365 365
366 366 NOTE: If you have 'automagic' enabled (via the command line option or with the
367 367 %automagic function), you don't need to type in the % explicitly. By default,
368 368 IPython ships with automagic on, so you should only rarely need the % escape.
369 369
370 370 Example: typing '%cd mydir' (without the quotes) changes you working directory
371 371 to 'mydir', if it exists.
372 372
373 373 You can define your own magic functions to extend the system. See the supplied
374 374 ipythonrc and example-magic.py files for details (in your ipython
375 375 configuration directory, typically $HOME/.ipython/).
376 376
377 377 You can also define your own aliased names for magic functions. In your
378 378 ipythonrc file, placing a line like:
379 379
380 380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
381 381
382 382 will define %pf as a new name for %profile.
383 383
384 384 You can also call magics in code using the ipmagic() function, which IPython
385 385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
386 386
387 387 For a list of the available magic functions, use %lsmagic. For a description
388 388 of any of them, type %magic_name?, e.g. '%cd?'.
389 389
390 390 Currently the magic system has the following functions:\n"""
391 391
392 392 mesc = self.shell.ESC_MAGIC
393 393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
394 394 "\n\n%s%s\n\n%s" % (outmsg,
395 395 magic_docs,mesc,mesc,
396 396 (' '+mesc).join(self.lsmagic()),
397 397 Magic.auto_status[self.shell.rc.automagic] ) )
398 398
399 399 page(outmsg,screen_lines=self.shell.rc.screen_length)
400 400
401 401 def magic_automagic(self, parameter_s = ''):
402 402 """Make magic functions callable without having to type the initial %.
403 403
404 404 Toggles on/off (when off, you must call it as %automagic, of
405 405 course). Note that magic functions have lowest priority, so if there's
406 406 a variable whose name collides with that of a magic fn, automagic
407 407 won't work for that function (you get the variable instead). However,
408 408 if you delete the variable (del var), the previously shadowed magic
409 409 function becomes visible to automagic again."""
410 410
411 411 rc = self.shell.rc
412 412 rc.automagic = not rc.automagic
413 413 print '\n' + Magic.auto_status[rc.automagic]
414 414
415 415 def magic_autocall(self, parameter_s = ''):
416 416 """Make functions callable without having to type parentheses.
417 417
418 418 This toggles the autocall command line option on and off."""
419 419
420 420 rc = self.shell.rc
421 421 rc.autocall = not rc.autocall
422 422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
423 423
424 424 def magic_autoindent(self, parameter_s = ''):
425 425 """Toggle autoindent on/off (if available)."""
426 426
427 427 self.shell.set_autoindent()
428 428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
429 429
430 430 def magic_system_verbose(self, parameter_s = ''):
431 431 """Toggle verbose printing of system calls on/off."""
432 432
433 433 self.shell.rc_set_toggle('system_verbose')
434 434 print "System verbose printing is:",\
435 435 ['OFF','ON'][self.shell.rc.system_verbose]
436 436
437 437 def magic_history(self, parameter_s = ''):
438 438 """Print input history (_i<n> variables), with most recent last.
439 439
440 440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
441 441 %history [-n] n -> print at most n inputs\\
442 442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
443 443
444 444 Each input's number <n> is shown, and is accessible as the
445 445 automatically generated variable _i<n>. Multi-line statements are
446 446 printed starting at a new line for easy copy/paste.
447 447
448 448 If option -n is used, input numbers are not printed. This is useful if
449 449 you want to get a printout of many lines which can be directly pasted
450 450 into a text editor.
451 451
452 452 This feature is only available if numbered prompts are in use."""
453 453
454 if not self.shell.outputcache.do_full_cache:
454 shell = self.shell
455 if not shell.outputcache.do_full_cache:
455 456 print 'This feature is only available if numbered prompts are in use.'
456 457 return
457 458 opts,args = self.parse_options(parameter_s,'n',mode='list')
458 459
460 input_hist = shell.input_hist
459 461 default_length = 40
460 462 if len(args) == 0:
461 final = self.shell.outputcache.prompt_count
463 final = len(input_hist)
462 464 init = max(1,final-default_length)
463 465 elif len(args) == 1:
464 final = self.shell.outputcache.prompt_count
466 final = len(input_hist)
465 467 init = max(1,final-int(args[0]))
466 468 elif len(args) == 2:
467 469 init,final = map(int,args)
468 470 else:
469 471 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
470 472 print self.magic_hist.__doc__
471 473 return
472 474 width = len(str(final))
473 475 line_sep = ['','\n']
474 input_hist = self.shell.input_hist
475 476 print_nums = not opts.has_key('n')
476 477 for in_num in range(init,final):
477 478 inline = input_hist[in_num]
478 multiline = inline.count('\n') > 1
479 multiline = int(inline.count('\n') > 1)
479 480 if print_nums:
480 print str(in_num).ljust(width)+':'+ line_sep[multiline],
481 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
482 inline.startswith('#!'):
483 print inline[1:],
484 else:
485 print inline,
481 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
482 print inline,
486 483
487 484 def magic_hist(self, parameter_s=''):
488 485 """Alternate name for %history."""
489 486 return self.magic_history(parameter_s)
490 487
491 488 def magic_p(self, parameter_s=''):
492 489 """Just a short alias for Python's 'print'."""
493 490 exec 'print ' + parameter_s in self.shell.user_ns
494 491
495 492 def magic_r(self, parameter_s=''):
496 493 """Repeat previous input.
497 494
498 495 If given an argument, repeats the previous command which starts with
499 496 the same string, otherwise it just repeats the previous input.
500 497
501 498 Shell escaped commands (with ! as first character) are not recognized
502 499 by this system, only pure python code and magic commands.
503 500 """
504 501
505 502 start = parameter_s.strip()
506 503 esc_magic = self.shell.ESC_MAGIC
507 504 # Identify magic commands even if automagic is on (which means
508 505 # the in-memory version is different from that typed by the user).
509 506 if self.shell.rc.automagic:
510 507 start_magic = esc_magic+start
511 508 else:
512 509 start_magic = start
513 510 # Look through the input history in reverse
514 511 for n in range(len(self.shell.input_hist)-2,0,-1):
515 512 input = self.shell.input_hist[n]
516 513 # skip plain 'r' lines so we don't recurse to infinity
517 514 if input != 'ipmagic("r")\n' and \
518 515 (input.startswith(start) or input.startswith(start_magic)):
519 516 #print 'match',`input` # dbg
520 517 print 'Executing:',input,
521 518 self.shell.runlines(input)
522 519 return
523 520 print 'No previous input matching `%s` found.' % start
524 521
525 522 def magic_page(self, parameter_s=''):
526 523 """Pretty print the object and display it through a pager.
527 524
528 525 If no parameter is given, use _ (last output)."""
529 526 # After a function contributed by Olivier Aubert, slightly modified.
530 527
531 528 oname = parameter_s and parameter_s or '_'
532 529 info = self._ofind(oname)
533 530 if info['found']:
534 531 page(pformat(info['obj']))
535 532 else:
536 533 print 'Object `%s` not found' % oname
537 534
538 535 def magic_profile(self, parameter_s=''):
539 536 """Print your currently active IPyhton profile."""
540 537 if self.shell.rc.profile:
541 538 printpl('Current IPython profile: $self.shell.rc.profile.')
542 539 else:
543 540 print 'No profile active.'
544 541
545 542 def _inspect(self,meth,oname,**kw):
546 543 """Generic interface to the inspector system.
547 544
548 545 This function is meant to be called by pdef, pdoc & friends."""
549 546
550 547 oname = oname.strip()
551 548 info = Struct(self._ofind(oname))
552 549 if info.found:
553 550 pmethod = getattr(self.shell.inspector,meth)
554 551 formatter = info.ismagic and self.format_screen or None
555 552 if meth == 'pdoc':
556 553 pmethod(info.obj,oname,formatter)
557 554 elif meth == 'pinfo':
558 555 pmethod(info.obj,oname,formatter,info,**kw)
559 556 else:
560 557 pmethod(info.obj,oname)
561 558 else:
562 559 print 'Object `%s` not found.' % oname
563 560 return 'not found' # so callers can take other action
564 561
565 562 def magic_pdef(self, parameter_s=''):
566 563 """Print the definition header for any callable object.
567 564
568 565 If the object is a class, print the constructor information."""
569 566 self._inspect('pdef',parameter_s)
570 567
571 568 def magic_pdoc(self, parameter_s=''):
572 569 """Print the docstring for an object.
573 570
574 571 If the given object is a class, it will print both the class and the
575 572 constructor docstrings."""
576 573 self._inspect('pdoc',parameter_s)
577 574
578 575 def magic_psource(self, parameter_s=''):
579 576 """Print (or run through pager) the source code for an object."""
580 577 self._inspect('psource',parameter_s)
581 578
582 579 def magic_pfile(self, parameter_s=''):
583 580 """Print (or run through pager) the file where an object is defined.
584 581
585 582 The file opens at the line where the object definition begins. IPython
586 583 will honor the environment variable PAGER if set, and otherwise will
587 584 do its best to print the file in a convenient form.
588 585
589 586 If the given argument is not an object currently defined, IPython will
590 587 try to interpret it as a filename (automatically adding a .py extension
591 588 if needed). You can thus use %pfile as a syntax highlighting code
592 589 viewer."""
593 590
594 591 # first interpret argument as an object name
595 592 out = self._inspect('pfile',parameter_s)
596 593 # if not, try the input as a filename
597 594 if out == 'not found':
598 595 try:
599 596 filename = get_py_filename(parameter_s)
600 597 except IOError,msg:
601 598 print msg
602 599 return
603 600 page(self.shell.inspector.format(file(filename).read()))
604 601
605 602 def magic_pinfo(self, parameter_s=''):
606 603 """Provide detailed information about an object.
607 604
608 605 '%pinfo object' is just a synonym for object? or ?object."""
609 606
610 607 #print 'pinfo par: <%s>' % parameter_s # dbg
611 608
612 609 # detail_level: 0 -> obj? , 1 -> obj??
613 610 detail_level = 0
614 611 # We need to detect if we got called as 'pinfo pinfo foo', which can
615 612 # happen if the user types 'pinfo foo?' at the cmd line.
616 613 pinfo,qmark1,oname,qmark2 = \
617 614 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
618 615 if pinfo or qmark1 or qmark2:
619 616 detail_level = 1
620 617 if "*" in oname:
621 618 self.magic_psearch(oname)
622 619 else:
623 620 self._inspect('pinfo',oname,detail_level=detail_level)
624 621
625 622 def magic_psearch(self, parameter_s=''):
626 623 """Search for object in namespaces by wildcard.
627 624
628 625 %psearch [options] PATTERN [OBJECT TYPE]
629 626
630 627 Note: ? can be used as a synonym for %psearch, at the beginning or at
631 628 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
632 629 rest of the command line must be unchanged (options come first), so
633 630 for example the following forms are equivalent
634 631
635 632 %psearch -i a* function
636 633 -i a* function?
637 634 ?-i a* function
638 635
639 636 Arguments:
640 637
641 638 PATTERN
642 639
643 640 where PATTERN is a string containing * as a wildcard similar to its
644 641 use in a shell. The pattern is matched in all namespaces on the
645 642 search path. By default objects starting with a single _ are not
646 643 matched, many IPython generated objects have a single
647 644 underscore. The default is case insensitive matching. Matching is
648 645 also done on the attributes of objects and not only on the objects
649 646 in a module.
650 647
651 648 [OBJECT TYPE]
652 649
653 650 Is the name of a python type from the types module. The name is
654 651 given in lowercase without the ending type, ex. StringType is
655 652 written string. By adding a type here only objects matching the
656 653 given type are matched. Using all here makes the pattern match all
657 654 types (this is the default).
658 655
659 656 Options:
660 657
661 658 -a: makes the pattern match even objects whose names start with a
662 659 single underscore. These names are normally ommitted from the
663 660 search.
664 661
665 662 -i/-c: make the pattern case insensitive/sensitive. If neither of
666 663 these options is given, the default is read from your ipythonrc
667 664 file. The option name which sets this value is
668 665 'wildcards_case_sensitive'. If this option is not specified in your
669 666 ipythonrc file, IPython's internal default is to do a case sensitive
670 667 search.
671 668
672 669 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
673 670 specifiy can be searched in any of the following namespaces:
674 671 'builtin', 'user', 'user_global','internal', 'alias', where
675 672 'builtin' and 'user' are the search defaults. Note that you should
676 673 not use quotes when specifying namespaces.
677 674
678 675 'Builtin' contains the python module builtin, 'user' contains all
679 676 user data, 'alias' only contain the shell aliases and no python
680 677 objects, 'internal' contains objects used by IPython. The
681 678 'user_global' namespace is only used by embedded IPython instances,
682 679 and it contains module-level globals. You can add namespaces to the
683 680 search with -s or exclude them with -e (these options can be given
684 681 more than once).
685 682
686 683 Examples:
687 684
688 685 %psearch a* -> objects beginning with an a
689 686 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
690 687 %psearch a* function -> all functions beginning with an a
691 688 %psearch re.e* -> objects beginning with an e in module re
692 689 %psearch r*.e* -> objects that start with e in modules starting in r
693 690 %psearch r*.* string -> all strings in modules beginning with r
694 691
695 692 Case sensitve search:
696 693
697 694 %psearch -c a* list all object beginning with lower case a
698 695
699 696 Show objects beginning with a single _:
700 697
701 698 %psearch -a _* list objects beginning with a single underscore"""
702 699
703 700 # default namespaces to be searched
704 701 def_search = ['user','builtin']
705 702
706 703 # Process options/args
707 704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
708 705 opt = opts.get
709 706 shell = self.shell
710 707 psearch = shell.inspector.psearch
711 708
712 709 # select case options
713 710 if opts.has_key('i'):
714 711 ignore_case = True
715 712 elif opts.has_key('c'):
716 713 ignore_case = False
717 714 else:
718 715 ignore_case = not shell.rc.wildcards_case_sensitive
719 716
720 717 # Build list of namespaces to search from user options
721 718 def_search.extend(opt('s',[]))
722 719 ns_exclude = ns_exclude=opt('e',[])
723 720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
724 721
725 722 # Call the actual search
726 723 try:
727 724 psearch(args,shell.ns_table,ns_search,
728 725 show_all=opt('a'),ignore_case=ignore_case)
729 726 except:
730 727 shell.showtraceback()
731 728
732 729 def magic_who_ls(self, parameter_s=''):
733 730 """Return a sorted list of all interactive variables.
734 731
735 732 If arguments are given, only variables of types matching these
736 733 arguments are returned."""
737 734
738 735 user_ns = self.shell.user_ns
739 736 out = []
740 737 typelist = parameter_s.split()
741 738 for i in self.shell.user_ns.keys():
742 739 if not (i.startswith('_') or i.startswith('_i')) \
743 740 and not (self.shell.internal_ns.has_key(i) or
744 741 self.shell.user_config_ns.has_key(i)):
745 742 if typelist:
746 743 if type(user_ns[i]).__name__ in typelist:
747 744 out.append(i)
748 745 else:
749 746 out.append(i)
750 747 out.sort()
751 748 return out
752 749
753 750 def magic_who(self, parameter_s=''):
754 751 """Print all interactive variables, with some minimal formatting.
755 752
756 753 If any arguments are given, only variables whose type matches one of
757 754 these are printed. For example:
758 755
759 756 %who function str
760 757
761 758 will only list functions and strings, excluding all other types of
762 759 variables. To find the proper type names, simply use type(var) at a
763 760 command line to see how python prints type names. For example:
764 761
765 762 In [1]: type('hello')\\
766 763 Out[1]: <type 'str'>
767 764
768 765 indicates that the type name for strings is 'str'.
769 766
770 767 %who always excludes executed names loaded through your configuration
771 768 file and things which are internal to IPython.
772 769
773 770 This is deliberate, as typically you may load many modules and the
774 771 purpose of %who is to show you only what you've manually defined."""
775 772
776 773 varlist = self.magic_who_ls(parameter_s)
777 774 if not varlist:
778 775 print 'Interactive namespace is empty.'
779 776 return
780 777
781 778 # if we have variables, move on...
782 779
783 780 # stupid flushing problem: when prompts have no separators, stdout is
784 781 # getting lost. I'm starting to think this is a python bug. I'm having
785 782 # to force a flush with a print because even a sys.stdout.flush
786 783 # doesn't seem to do anything!
787 784
788 785 count = 0
789 786 for i in varlist:
790 787 print i+'\t',
791 788 count += 1
792 789 if count > 8:
793 790 count = 0
794 791 print
795 792 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
796 793
797 794 print # well, this does force a flush at the expense of an extra \n
798 795
799 796 def magic_whos(self, parameter_s=''):
800 797 """Like %who, but gives some extra information about each variable.
801 798
802 799 The same type filtering of %who can be applied here.
803 800
804 801 For all variables, the type is printed. Additionally it prints:
805 802
806 803 - For {},[],(): their length.
807 804
808 805 - For Numeric arrays, a summary with shape, number of elements,
809 806 typecode and size in memory.
810 807
811 808 - Everything else: a string representation, snipping their middle if
812 809 too long."""
813 810
814 811 varnames = self.magic_who_ls(parameter_s)
815 812 if not varnames:
816 813 print 'Interactive namespace is empty.'
817 814 return
818 815
819 816 # if we have variables, move on...
820 817
821 818 # for these types, show len() instead of data:
822 819 seq_types = [types.DictType,types.ListType,types.TupleType]
823 820
824 821 # for Numeric arrays, display summary info
825 822 try:
826 823 import Numeric
827 824 except ImportError:
828 825 array_type = None
829 826 else:
830 827 array_type = Numeric.ArrayType.__name__
831 828
832 829 # Find all variable names and types so we can figure out column sizes
833 830 get_vars = lambda i: self.shell.user_ns[i]
834 831 type_name = lambda v: type(v).__name__
835 832 varlist = map(get_vars,varnames)
836 833
837 834 typelist = []
838 835 for vv in varlist:
839 836 tt = type_name(vv)
840 837 if tt=='instance':
841 838 typelist.append(str(vv.__class__))
842 839 else:
843 840 typelist.append(tt)
844 841
845 842 # column labels and # of spaces as separator
846 843 varlabel = 'Variable'
847 844 typelabel = 'Type'
848 845 datalabel = 'Data/Info'
849 846 colsep = 3
850 847 # variable format strings
851 848 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
852 849 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
853 850 aformat = "%s: %s elems, type `%s`, %s bytes"
854 851 # find the size of the columns to format the output nicely
855 852 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
856 853 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
857 854 # table header
858 855 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
859 856 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
860 857 # and the table itself
861 858 kb = 1024
862 859 Mb = 1048576 # kb**2
863 860 for vname,var,vtype in zip(varnames,varlist,typelist):
864 861 print itpl(vformat),
865 862 if vtype in seq_types:
866 863 print len(var)
867 864 elif vtype==array_type:
868 865 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
869 866 vsize = Numeric.size(var)
870 867 vbytes = vsize*var.itemsize()
871 868 if vbytes < 100000:
872 869 print aformat % (vshape,vsize,var.typecode(),vbytes)
873 870 else:
874 871 print aformat % (vshape,vsize,var.typecode(),vbytes),
875 872 if vbytes < Mb:
876 873 print '(%s kb)' % (vbytes/kb,)
877 874 else:
878 875 print '(%s Mb)' % (vbytes/Mb,)
879 876 else:
880 877 vstr = str(var).replace('\n','\\n')
881 878 if len(vstr) < 50:
882 879 print vstr
883 880 else:
884 881 printpl(vfmt_short)
885 882
886 883 def magic_reset(self, parameter_s=''):
887 884 """Resets the namespace by removing all names defined by the user.
888 885
889 886 Input/Output history are left around in case you need them."""
890 887
891 888 ans = raw_input(
892 889 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
893 890 if not ans.lower() == 'y':
894 891 print 'Nothing done.'
895 892 return
896 893 user_ns = self.shell.user_ns
897 894 for i in self.magic_who_ls():
898 895 del(user_ns[i])
899 896
900 897 def magic_config(self,parameter_s=''):
901 898 """Show IPython's internal configuration."""
902 899
903 900 page('Current configuration structure:\n'+
904 901 pformat(self.shell.rc.dict()))
905 902
906 903 def magic_logstart(self,parameter_s=''):
907 904 """Start logging anywhere in a session.
908 905
909 906 %logstart [-o|-t] [log_name [log_mode]]
910 907
911 908 If no name is given, it defaults to a file named 'ipython_log.py' in your
912 909 current directory, in 'rotate' mode (see below).
913 910
914 911 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
915 912 history up to that point and then continues logging.
916 913
917 914 %logstart takes a second optional parameter: logging mode. This can be one
918 915 of (note that the modes are given unquoted):\\
919 916 append: well, that says it.\\
920 917 backup: rename (if exists) to name~ and start name.\\
921 918 global: single logfile in your home dir, appended to.\\
922 919 over : overwrite existing log.\\
923 920 rotate: create rotating logs name.1~, name.2~, etc.
924 921
925 922 Options:
926 923
927 924 -o: log also IPython's output. In this mode, all commands which
928 925 generate an Out[NN] prompt are recorded to the logfile, right after
929 926 their corresponding input line. The output lines are always
930 927 prepended with a '#[Out]# ' marker, so that the log remains valid
931 928 Python code.
932 929
933 930 Since this marker is always the same, filtering only the output from
934 931 a log is very easy, using for example a simple awk call:
935 932
936 933 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
937 934
938 935 -t: put timestamps before each input line logged (these are put in
939 936 comments)."""
940 937
941 938 opts,par = self.parse_options(parameter_s,'ot')
942 939 log_output = 'o' in opts
943 940 timestamp = 't' in opts
944 941
945 942 rc = self.shell.rc
946 943 logger = self.shell.logger
947 944
948 945 # if no args are given, the defaults set in the logger constructor by
949 946 # ipytohn remain valid
950 947 if par:
951 948 try:
952 949 logfname,logmode = par.split()
953 950 except:
954 951 logfname = par
955 952 logmode = 'backup'
956 953 else:
957 954 logfname = logger.logfname
958 955 logmode = logger.logmode
959 956 # put logfname into rc struct as if it had been called on the command
960 957 # line, so it ends up saved in the log header Save it in case we need
961 958 # to restore it...
962 959 old_logfile = rc.opts.get('logfile','')
963 960 if logfname:
964 961 logfname = os.path.expanduser(logfname)
965 962 rc.opts.logfile = logfname
966 963 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
967 964 try:
968 965 started = logger.logstart(logfname,loghead,logmode,
969 966 log_output,timestamp)
970 967 except:
971 968 rc.opts.logfile = old_logfile
972 969 warn("Couldn't start log: %s" % sys.exc_info()[1])
973 970 else:
974 971 # log input history up to this point, optionally interleaving
975 972 # output if requested
976 973
977 974 if timestamp:
978 975 # disable timestamping for the previous history, since we've
979 976 # lost those already (no time machine here).
980 977 logger.timestamp = False
981 978 if log_output:
982 979 log_write = logger.log_write
983 980 input_hist = self.shell.input_hist
984 981 output_hist = self.shell.output_hist
985 982 for n in range(1,len(input_hist)-1):
986 983 log_write(input_hist[n].rstrip())
987 984 if n in output_hist:
988 985 log_write(repr(output_hist[n]),'output')
989 986 else:
990 987 logger.log_write(self.shell.input_hist[1:])
991 988 if timestamp:
992 989 # re-enable timestamping
993 990 logger.timestamp = True
994 991
995 992 print ('Activating auto-logging. '
996 993 'Current session state plus future input saved.')
997 994 logger.logstate()
998 995
999 996 def magic_logoff(self,parameter_s=''):
1000 997 """Temporarily stop logging.
1001 998
1002 999 You must have previously started logging."""
1003 1000 self.shell.logger.switch_log(0)
1004 1001
1005 1002 def magic_logon(self,parameter_s=''):
1006 1003 """Restart logging.
1007 1004
1008 1005 This function is for restarting logging which you've temporarily
1009 1006 stopped with %logoff. For starting logging for the first time, you
1010 1007 must use the %logstart function, which allows you to specify an
1011 1008 optional log filename."""
1012 1009
1013 1010 self.shell.logger.switch_log(1)
1014 1011
1015 1012 def magic_logstate(self,parameter_s=''):
1016 1013 """Print the status of the logging system."""
1017 1014
1018 1015 self.shell.logger.logstate()
1019 1016
1020 1017 def magic_pdb(self, parameter_s=''):
1021 1018 """Control the calling of the pdb interactive debugger.
1022 1019
1023 1020 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1024 1021 argument it works as a toggle.
1025 1022
1026 1023 When an exception is triggered, IPython can optionally call the
1027 1024 interactive pdb debugger after the traceback printout. %pdb toggles
1028 1025 this feature on and off."""
1029 1026
1030 1027 par = parameter_s.strip().lower()
1031 1028
1032 1029 if par:
1033 1030 try:
1034 1031 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1035 1032 except KeyError:
1036 1033 print ('Incorrect argument. Use on/1, off/0, '
1037 1034 'or nothing for a toggle.')
1038 1035 return
1039 1036 else:
1040 1037 # toggle
1041 1038 new_pdb = not self.shell.InteractiveTB.call_pdb
1042 1039
1043 1040 # set on the shell
1044 1041 self.shell.call_pdb = new_pdb
1045 1042 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1046 1043
1047 1044 def magic_prun(self, parameter_s ='',user_mode=1,
1048 1045 opts=None,arg_lst=None,prog_ns=None):
1049 1046
1050 1047 """Run a statement through the python code profiler.
1051 1048
1052 1049 Usage:\\
1053 1050 %prun [options] statement
1054 1051
1055 1052 The given statement (which doesn't require quote marks) is run via the
1056 1053 python profiler in a manner similar to the profile.run() function.
1057 1054 Namespaces are internally managed to work correctly; profile.run
1058 1055 cannot be used in IPython because it makes certain assumptions about
1059 1056 namespaces which do not hold under IPython.
1060 1057
1061 1058 Options:
1062 1059
1063 1060 -l <limit>: you can place restrictions on what or how much of the
1064 1061 profile gets printed. The limit value can be:
1065 1062
1066 1063 * A string: only information for function names containing this string
1067 1064 is printed.
1068 1065
1069 1066 * An integer: only these many lines are printed.
1070 1067
1071 1068 * A float (between 0 and 1): this fraction of the report is printed
1072 1069 (for example, use a limit of 0.4 to see the topmost 40% only).
1073 1070
1074 1071 You can combine several limits with repeated use of the option. For
1075 1072 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1076 1073 information about class constructors.
1077 1074
1078 1075 -r: return the pstats.Stats object generated by the profiling. This
1079 1076 object has all the information about the profile in it, and you can
1080 1077 later use it for further analysis or in other functions.
1081 1078
1082 1079 Since magic functions have a particular form of calling which prevents
1083 1080 you from writing something like:\\
1084 1081 In [1]: p = %prun -r print 4 # invalid!\\
1085 1082 you must instead use IPython's automatic variables to assign this:\\
1086 1083 In [1]: %prun -r print 4 \\
1087 1084 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1088 1085 In [2]: stats = _
1089 1086
1090 1087 If you really need to assign this value via an explicit function call,
1091 1088 you can always tap directly into the true name of the magic function
1092 1089 by using the ipmagic function (which IPython automatically adds to the
1093 1090 builtins):\\
1094 1091 In [3]: stats = ipmagic('prun','-r print 4')
1095 1092
1096 1093 You can type ipmagic? for more details on ipmagic.
1097 1094
1098 1095 -s <key>: sort profile by given key. You can provide more than one key
1099 1096 by using the option several times: '-s key1 -s key2 -s key3...'. The
1100 1097 default sorting key is 'time'.
1101 1098
1102 1099 The following is copied verbatim from the profile documentation
1103 1100 referenced below:
1104 1101
1105 1102 When more than one key is provided, additional keys are used as
1106 1103 secondary criteria when the there is equality in all keys selected
1107 1104 before them.
1108 1105
1109 1106 Abbreviations can be used for any key names, as long as the
1110 1107 abbreviation is unambiguous. The following are the keys currently
1111 1108 defined:
1112 1109
1113 1110 Valid Arg Meaning\\
1114 1111 "calls" call count\\
1115 1112 "cumulative" cumulative time\\
1116 1113 "file" file name\\
1117 1114 "module" file name\\
1118 1115 "pcalls" primitive call count\\
1119 1116 "line" line number\\
1120 1117 "name" function name\\
1121 1118 "nfl" name/file/line\\
1122 1119 "stdname" standard name\\
1123 1120 "time" internal time
1124 1121
1125 1122 Note that all sorts on statistics are in descending order (placing
1126 1123 most time consuming items first), where as name, file, and line number
1127 1124 searches are in ascending order (i.e., alphabetical). The subtle
1128 1125 distinction between "nfl" and "stdname" is that the standard name is a
1129 1126 sort of the name as printed, which means that the embedded line
1130 1127 numbers get compared in an odd way. For example, lines 3, 20, and 40
1131 1128 would (if the file names were the same) appear in the string order
1132 1129 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1133 1130 line numbers. In fact, sort_stats("nfl") is the same as
1134 1131 sort_stats("name", "file", "line").
1135 1132
1136 1133 -T <filename>: save profile results as shown on screen to a text
1137 1134 file. The profile is still shown on screen.
1138 1135
1139 1136 -D <filename>: save (via dump_stats) profile statistics to given
1140 1137 filename. This data is in a format understod by the pstats module, and
1141 1138 is generated by a call to the dump_stats() method of profile
1142 1139 objects. The profile is still shown on screen.
1143 1140
1144 1141 If you want to run complete programs under the profiler's control, use
1145 1142 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1146 1143 contains profiler specific options as described here.
1147 1144
1148 1145 You can read the complete documentation for the profile module with:\\
1149 1146 In [1]: import profile; profile.help() """
1150 1147
1151 1148 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1152 1149 # protect user quote marks
1153 1150 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1154 1151
1155 1152 if user_mode: # regular user call
1156 1153 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1157 1154 list_all=1)
1158 1155 namespace = self.shell.user_ns
1159 1156 else: # called to run a program by %run -p
1160 1157 try:
1161 1158 filename = get_py_filename(arg_lst[0])
1162 1159 except IOError,msg:
1163 1160 error(msg)
1164 1161 return
1165 1162
1166 1163 arg_str = 'execfile(filename,prog_ns)'
1167 1164 namespace = locals()
1168 1165
1169 1166 opts.merge(opts_def)
1170 1167
1171 1168 prof = profile.Profile()
1172 1169 try:
1173 1170 prof = prof.runctx(arg_str,namespace,namespace)
1174 1171 sys_exit = ''
1175 1172 except SystemExit:
1176 1173 sys_exit = """*** SystemExit exception caught in code being profiled."""
1177 1174
1178 1175 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1179 1176
1180 1177 lims = opts.l
1181 1178 if lims:
1182 1179 lims = [] # rebuild lims with ints/floats/strings
1183 1180 for lim in opts.l:
1184 1181 try:
1185 1182 lims.append(int(lim))
1186 1183 except ValueError:
1187 1184 try:
1188 1185 lims.append(float(lim))
1189 1186 except ValueError:
1190 1187 lims.append(lim)
1191 1188
1192 1189 # trap output
1193 1190 sys_stdout = sys.stdout
1194 1191 stdout_trap = StringIO()
1195 1192 try:
1196 1193 sys.stdout = stdout_trap
1197 1194 stats.print_stats(*lims)
1198 1195 finally:
1199 1196 sys.stdout = sys_stdout
1200 1197 output = stdout_trap.getvalue()
1201 1198 output = output.rstrip()
1202 1199
1203 1200 page(output,screen_lines=self.shell.rc.screen_length)
1204 1201 print sys_exit,
1205 1202
1206 1203 dump_file = opts.D[0]
1207 1204 text_file = opts.T[0]
1208 1205 if dump_file:
1209 1206 prof.dump_stats(dump_file)
1210 1207 print '\n*** Profile stats marshalled to file',\
1211 1208 `dump_file`+'.',sys_exit
1212 1209 if text_file:
1213 1210 file(text_file,'w').write(output)
1214 1211 print '\n*** Profile printout saved to text file',\
1215 1212 `text_file`+'.',sys_exit
1216 1213
1217 1214 if opts.has_key('r'):
1218 1215 return stats
1219 1216 else:
1220 1217 return None
1221 1218
1222 1219 def magic_run(self, parameter_s ='',runner=None):
1223 1220 """Run the named file inside IPython as a program.
1224 1221
1225 1222 Usage:\\
1226 1223 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1227 1224
1228 1225 Parameters after the filename are passed as command-line arguments to
1229 1226 the program (put in sys.argv). Then, control returns to IPython's
1230 1227 prompt.
1231 1228
1232 1229 This is similar to running at a system prompt:\\
1233 1230 $ python file args\\
1234 1231 but with the advantage of giving you IPython's tracebacks, and of
1235 1232 loading all variables into your interactive namespace for further use
1236 1233 (unless -p is used, see below).
1237 1234
1238 1235 The file is executed in a namespace initially consisting only of
1239 1236 __name__=='__main__' and sys.argv constructed as indicated. It thus
1240 1237 sees its environment as if it were being run as a stand-alone
1241 1238 program. But after execution, the IPython interactive namespace gets
1242 1239 updated with all variables defined in the program (except for __name__
1243 1240 and sys.argv). This allows for very convenient loading of code for
1244 1241 interactive work, while giving each program a 'clean sheet' to run in.
1245 1242
1246 1243 Options:
1247 1244
1248 1245 -n: __name__ is NOT set to '__main__', but to the running file's name
1249 1246 without extension (as python does under import). This allows running
1250 1247 scripts and reloading the definitions in them without calling code
1251 1248 protected by an ' if __name__ == "__main__" ' clause.
1252 1249
1253 1250 -i: run the file in IPython's namespace instead of an empty one. This
1254 1251 is useful if you are experimenting with code written in a text editor
1255 1252 which depends on variables defined interactively.
1256 1253
1257 1254 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1258 1255 being run. This is particularly useful if IPython is being used to
1259 1256 run unittests, which always exit with a sys.exit() call. In such
1260 1257 cases you are interested in the output of the test results, not in
1261 1258 seeing a traceback of the unittest module.
1262 1259
1263 1260 -t: print timing information at the end of the run. IPython will give
1264 1261 you an estimated CPU time consumption for your script, which under
1265 1262 Unix uses the resource module to avoid the wraparound problems of
1266 1263 time.clock(). Under Unix, an estimate of time spent on system tasks
1267 1264 is also given (for Windows platforms this is reported as 0.0).
1268 1265
1269 1266 If -t is given, an additional -N<N> option can be given, where <N>
1270 1267 must be an integer indicating how many times you want the script to
1271 1268 run. The final timing report will include total and per run results.
1272 1269
1273 1270 For example (testing the script uniq_stable.py):
1274 1271
1275 1272 In [1]: run -t uniq_stable
1276 1273
1277 1274 IPython CPU timings (estimated):\\
1278 1275 User : 0.19597 s.\\
1279 1276 System: 0.0 s.\\
1280 1277
1281 1278 In [2]: run -t -N5 uniq_stable
1282 1279
1283 1280 IPython CPU timings (estimated):\\
1284 1281 Total runs performed: 5\\
1285 1282 Times : Total Per run\\
1286 1283 User : 0.910862 s, 0.1821724 s.\\
1287 1284 System: 0.0 s, 0.0 s.
1288 1285
1289 1286 -d: run your program under the control of pdb, the Python debugger.
1290 1287 This allows you to execute your program step by step, watch variables,
1291 1288 etc. Internally, what IPython does is similar to calling:
1292 1289
1293 1290 pdb.run('execfile("YOURFILENAME")')
1294 1291
1295 1292 with a breakpoint set on line 1 of your file. You can change the line
1296 1293 number for this automatic breakpoint to be <N> by using the -bN option
1297 1294 (where N must be an integer). For example:
1298 1295
1299 1296 %run -d -b40 myscript
1300 1297
1301 1298 will set the first breakpoint at line 40 in myscript.py. Note that
1302 1299 the first breakpoint must be set on a line which actually does
1303 1300 something (not a comment or docstring) for it to stop execution.
1304 1301
1305 1302 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1306 1303 first enter 'c' (without qoutes) to start execution up to the first
1307 1304 breakpoint.
1308 1305
1309 1306 Entering 'help' gives information about the use of the debugger. You
1310 1307 can easily see pdb's full documentation with "import pdb;pdb.help()"
1311 1308 at a prompt.
1312 1309
1313 1310 -p: run program under the control of the Python profiler module (which
1314 1311 prints a detailed report of execution times, function calls, etc).
1315 1312
1316 1313 You can pass other options after -p which affect the behavior of the
1317 1314 profiler itself. See the docs for %prun for details.
1318 1315
1319 1316 In this mode, the program's variables do NOT propagate back to the
1320 1317 IPython interactive namespace (because they remain in the namespace
1321 1318 where the profiler executes them).
1322 1319
1323 1320 Internally this triggers a call to %prun, see its documentation for
1324 1321 details on the options available specifically for profiling."""
1325 1322
1326 1323 # get arguments and set sys.argv for program to be run.
1327 1324 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1328 1325 mode='list',list_all=1)
1329 1326
1330 1327 try:
1331 1328 filename = get_py_filename(arg_lst[0])
1332 1329 except IndexError:
1333 1330 warn('you must provide at least a filename.')
1334 1331 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1335 1332 return
1336 1333 except IOError,msg:
1337 1334 error(msg)
1338 1335 return
1339 1336
1340 1337 # Control the response to exit() calls made by the script being run
1341 1338 exit_ignore = opts.has_key('e')
1342 1339
1343 1340 # Make sure that the running script gets a proper sys.argv as if it
1344 1341 # were run from a system shell.
1345 1342 save_argv = sys.argv # save it for later restoring
1346 1343 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1347 1344
1348 1345 if opts.has_key('i'):
1349 1346 prog_ns = self.shell.user_ns
1350 1347 __name__save = self.shell.user_ns['__name__']
1351 1348 prog_ns['__name__'] = '__main__'
1352 1349 else:
1353 1350 if opts.has_key('n'):
1354 1351 name = os.path.splitext(os.path.basename(filename))[0]
1355 1352 else:
1356 1353 name = '__main__'
1357 1354 prog_ns = {'__name__':name}
1358 1355
1359 # pickle fix. See iplib for an explanation
1356 # pickle fix. See iplib for an explanation. But we need to make sure
1357 # that, if we overwrite __main__, we replace it at the end
1358 if prog_ns['__name__'] == '__main__':
1359 restore_main = sys.modules['__main__']
1360 else:
1361 restore_main = False
1362
1360 1363 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1361 1364
1362 1365 stats = None
1363 1366 try:
1364 1367 if opts.has_key('p'):
1365 1368 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1366 1369 else:
1367 1370 if opts.has_key('d'):
1368 1371 deb = Debugger.Pdb(self.shell.rc.colors)
1369 1372 # reset Breakpoint state, which is moronically kept
1370 1373 # in a class
1371 1374 bdb.Breakpoint.next = 1
1372 1375 bdb.Breakpoint.bplist = {}
1373 1376 bdb.Breakpoint.bpbynumber = [None]
1374 1377 # Set an initial breakpoint to stop execution
1375 1378 maxtries = 10
1376 1379 bp = int(opts.get('b',[1])[0])
1377 1380 checkline = deb.checkline(filename,bp)
1378 1381 if not checkline:
1379 1382 for bp in range(bp+1,bp+maxtries+1):
1380 1383 if deb.checkline(filename,bp):
1381 1384 break
1382 1385 else:
1383 1386 msg = ("\nI failed to find a valid line to set "
1384 1387 "a breakpoint\n"
1385 1388 "after trying up to line: %s.\n"
1386 1389 "Please set a valid breakpoint manually "
1387 1390 "with the -b option." % bp)
1388 1391 error(msg)
1389 1392 return
1390 1393 # if we find a good linenumber, set the breakpoint
1391 1394 deb.do_break('%s:%s' % (filename,bp))
1392 1395 # Start file run
1393 1396 print "NOTE: Enter 'c' at the",
1394 1397 print "ipdb> prompt to start your script."
1395 1398 try:
1396 1399 deb.run('execfile("%s")' % filename,prog_ns)
1397 1400 except:
1398 1401 etype, value, tb = sys.exc_info()
1399 1402 # Skip three frames in the traceback: the %run one,
1400 1403 # one inside bdb.py, and the command-line typed by the
1401 1404 # user (run by exec in pdb itself).
1402 1405 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1403 1406 else:
1404 1407 if runner is None:
1405 1408 runner = self.shell.safe_execfile
1406 1409 if opts.has_key('t'):
1407 1410 try:
1408 1411 nruns = int(opts['N'][0])
1409 1412 if nruns < 1:
1410 1413 error('Number of runs must be >=1')
1411 1414 return
1412 1415 except (KeyError):
1413 1416 nruns = 1
1414 1417 if nruns == 1:
1415 1418 t0 = clock2()
1416 1419 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1417 1420 t1 = clock2()
1418 1421 t_usr = t1[0]-t0[0]
1419 1422 t_sys = t1[1]-t1[1]
1420 1423 print "\nIPython CPU timings (estimated):"
1421 1424 print " User : %10s s." % t_usr
1422 1425 print " System: %10s s." % t_sys
1423 1426 else:
1424 1427 runs = range(nruns)
1425 1428 t0 = clock2()
1426 1429 for nr in runs:
1427 1430 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1428 1431 t1 = clock2()
1429 1432 t_usr = t1[0]-t0[0]
1430 1433 t_sys = t1[1]-t1[1]
1431 1434 print "\nIPython CPU timings (estimated):"
1432 1435 print "Total runs performed:",nruns
1433 1436 print " Times : %10s %10s" % ('Total','Per run')
1434 1437 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1435 1438 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1436 1439
1437 1440 else:
1438 1441 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1439 1442 if opts.has_key('i'):
1440 1443 self.shell.user_ns['__name__'] = __name__save
1441 1444 else:
1442 1445 # update IPython interactive namespace
1443 1446 del prog_ns['__name__']
1444 1447 self.shell.user_ns.update(prog_ns)
1445 1448 finally:
1446 1449 sys.argv = save_argv
1450 if restore_main:
1451 sys.modules['__main__'] = restore_main
1447 1452 return stats
1448 1453
1449 1454 def magic_runlog(self, parameter_s =''):
1450 1455 """Run files as logs.
1451 1456
1452 1457 Usage:\\
1453 1458 %runlog file1 file2 ...
1454 1459
1455 1460 Run the named files (treating them as log files) in sequence inside
1456 1461 the interpreter, and return to the prompt. This is much slower than
1457 1462 %run because each line is executed in a try/except block, but it
1458 1463 allows running files with syntax errors in them.
1459 1464
1460 1465 Normally IPython will guess when a file is one of its own logfiles, so
1461 1466 you can typically use %run even for logs. This shorthand allows you to
1462 1467 force any file to be treated as a log file."""
1463 1468
1464 1469 for f in parameter_s.split():
1465 1470 self.shell.safe_execfile(f,self.shell.user_ns,
1466 1471 self.shell.user_ns,islog=1)
1467 1472
1468 1473 def magic_time(self,parameter_s = ''):
1469 1474 """Time execution of a Python statement or expression.
1470 1475
1471 1476 The CPU and wall clock times are printed, and the value of the
1472 1477 expression (if any) is returned. Note that under Win32, system time
1473 1478 is always reported as 0, since it can not be measured.
1474 1479
1475 1480 This function provides very basic timing functionality. In Python
1476 1481 2.3, the timeit module offers more control and sophistication, but for
1477 1482 now IPython supports Python 2.2, so we can not rely on timeit being
1478 1483 present.
1479 1484
1480 1485 Some examples:
1481 1486
1482 1487 In [1]: time 2**128
1483 1488 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1484 1489 Wall time: 0.00
1485 1490 Out[1]: 340282366920938463463374607431768211456L
1486 1491
1487 1492 In [2]: n = 1000000
1488 1493
1489 1494 In [3]: time sum(range(n))
1490 1495 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1491 1496 Wall time: 1.37
1492 1497 Out[3]: 499999500000L
1493 1498
1494 1499 In [4]: time print 'hello world'
1495 1500 hello world
1496 1501 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1497 1502 Wall time: 0.00
1498 1503 """
1499 1504
1500 1505 # fail immediately if the given expression can't be compiled
1501 1506 try:
1502 1507 mode = 'eval'
1503 1508 code = compile(parameter_s,'<timed eval>',mode)
1504 1509 except SyntaxError:
1505 1510 mode = 'exec'
1506 1511 code = compile(parameter_s,'<timed exec>',mode)
1507 1512 # skew measurement as little as possible
1508 1513 glob = self.shell.user_ns
1509 1514 clk = clock2
1510 1515 wtime = time.time
1511 1516 # time execution
1512 1517 wall_st = wtime()
1513 1518 if mode=='eval':
1514 1519 st = clk()
1515 1520 out = eval(code,glob)
1516 1521 end = clk()
1517 1522 else:
1518 1523 st = clk()
1519 1524 exec code in glob
1520 1525 end = clk()
1521 1526 out = None
1522 1527 wall_end = wtime()
1523 1528 # Compute actual times and report
1524 1529 wall_time = wall_end-wall_st
1525 1530 cpu_user = end[0]-st[0]
1526 1531 cpu_sys = end[1]-st[1]
1527 1532 cpu_tot = cpu_user+cpu_sys
1528 1533 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1529 1534 (cpu_user,cpu_sys,cpu_tot)
1530 1535 print "Wall time: %.2f" % wall_time
1531 1536 return out
1532 1537
1533 1538 def magic_macro(self,parameter_s = ''):
1534 1539 """Define a set of input lines as a macro for future re-execution.
1535 1540
1536 1541 Usage:\\
1537 1542 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1538 1543
1539 1544 This will define a global variable called `name` which is a string
1540 1545 made of joining the slices and lines you specify (n1,n2,... numbers
1541 1546 above) from your input history into a single string. This variable
1542 1547 acts like an automatic function which re-executes those lines as if
1543 1548 you had typed them. You just type 'name' at the prompt and the code
1544 1549 executes.
1545 1550
1546 1551 Note that the slices use the standard Python slicing notation (5:8
1547 1552 means include lines numbered 5,6,7).
1548 1553
1549 1554 For example, if your history contains (%hist prints it):
1550 1555
1551 1556 44: x=1\\
1552 1557 45: y=3\\
1553 1558 46: z=x+y\\
1554 1559 47: print x\\
1555 1560 48: a=5\\
1556 1561 49: print 'x',x,'y',y\\
1557 1562
1558 1563 you can create a macro with lines 44 through 47 (included) and line 49
1559 1564 called my_macro with:
1560 1565
1561 1566 In [51]: %macro my_macro 44:48 49
1562 1567
1563 1568 Now, typing `my_macro` (without quotes) will re-execute all this code
1564 1569 in one pass.
1565 1570
1566 1571 You don't need to give the line-numbers in order, and any given line
1567 1572 number can appear multiple times. You can assemble macros with any
1568 1573 lines from your input history in any order.
1569 1574
1570 1575 The macro is a simple object which holds its value in an attribute,
1571 1576 but IPython's display system checks for macros and executes them as
1572 1577 code instead of printing them when you type their name.
1573 1578
1574 1579 You can view a macro's contents by explicitly printing it with:
1575 1580
1576 1581 'print macro_name'.
1577 1582
1578 1583 For one-off cases which DON'T contain magic function calls in them you
1579 1584 can obtain similar results by explicitly executing slices from your
1580 1585 input history with:
1581 1586
1582 1587 In [60]: exec In[44:48]+In[49]"""
1583 1588
1584 1589 args = parameter_s.split()
1585 1590 name,ranges = args[0], args[1:]
1586 1591 #print 'rng',ranges # dbg
1587 1592 lines = self.extract_input_slices(ranges)
1588 1593 macro = Macro(lines)
1589 1594 self.shell.user_ns.update({name:macro})
1590 1595 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1591 1596 print 'Macro contents:'
1592 1597 print macro,
1593 1598
1594 1599 def magic_save(self,parameter_s = ''):
1595 1600 """Save a set of lines to a given filename.
1596 1601
1597 1602 Usage:\\
1598 1603 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1599 1604
1600 1605 This function uses the same syntax as %macro for line extraction, but
1601 1606 instead of creating a macro it saves the resulting string to the
1602 1607 filename you specify.
1603 1608
1604 1609 It adds a '.py' extension to the file if you don't do so yourself, and
1605 1610 it asks for confirmation before overwriting existing files."""
1606 1611
1607 1612 args = parameter_s.split()
1608 1613 fname,ranges = args[0], args[1:]
1609 1614 if not fname.endswith('.py'):
1610 1615 fname += '.py'
1611 1616 if os.path.isfile(fname):
1612 1617 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1613 1618 if ans.lower() not in ['y','yes']:
1614 1619 print 'Operation cancelled.'
1615 1620 return
1616 1621 cmds = ''.join(self.extract_input_slices(ranges))
1617 1622 f = file(fname,'w')
1618 1623 f.write(cmds)
1619 1624 f.close()
1620 1625 print 'The following commands were written to file `%s`:' % fname
1621 1626 print cmds
1622 1627
1623 1628 def magic_ed(self,parameter_s = ''):
1624 1629 """Alias to %edit."""
1625 1630 return self.magic_edit(parameter_s)
1626 1631
1627 1632 def magic_edit(self,parameter_s = '',last_call=['','']):
1628 1633 """Bring up an editor and execute the resulting code.
1629 1634
1630 1635 Usage:
1631 1636 %edit [options] [args]
1632 1637
1633 1638 %edit runs IPython's editor hook. The default version of this hook is
1634 1639 set to call the __IPYTHON__.rc.editor command. This is read from your
1635 1640 environment variable $EDITOR. If this isn't found, it will default to
1636 1641 vi under Linux/Unix and to notepad under Windows. See the end of this
1637 1642 docstring for how to change the editor hook.
1638 1643
1639 1644 You can also set the value of this editor via the command line option
1640 1645 '-editor' or in your ipythonrc file. This is useful if you wish to use
1641 1646 specifically for IPython an editor different from your typical default
1642 1647 (and for Windows users who typically don't set environment variables).
1643 1648
1644 1649 This command allows you to conveniently edit multi-line code right in
1645 1650 your IPython session.
1646 1651
1647 1652 If called without arguments, %edit opens up an empty editor with a
1648 1653 temporary file and will execute the contents of this file when you
1649 1654 close it (don't forget to save it!).
1650 1655
1651 1656 Options:
1652 1657
1653 1658 -p: this will call the editor with the same data as the previous time
1654 1659 it was used, regardless of how long ago (in your current session) it
1655 1660 was.
1656 1661
1657 1662 -x: do not execute the edited code immediately upon exit. This is
1658 1663 mainly useful if you are editing programs which need to be called with
1659 1664 command line arguments, which you can then do using %run.
1660 1665
1661 1666 Arguments:
1662 1667
1663 1668 If arguments are given, the following possibilites exist:
1664 1669
1665 1670 - The arguments are numbers or pairs of colon-separated numbers (like
1666 1671 1 4:8 9). These are interpreted as lines of previous input to be
1667 1672 loaded into the editor. The syntax is the same of the %macro command.
1668 1673
1669 1674 - If the argument doesn't start with a number, it is evaluated as a
1670 1675 variable and its contents loaded into the editor. You can thus edit
1671 1676 any string which contains python code (including the result of
1672 1677 previous edits).
1673 1678
1674 1679 - If the argument is the name of an object (other than a string),
1675 1680 IPython will try to locate the file where it was defined and open the
1676 1681 editor at the point where it is defined. You can use `%edit function`
1677 1682 to load an editor exactly at the point where 'function' is defined,
1678 1683 edit it and have the file be executed automatically.
1679 1684
1680 1685 Note: opening at an exact line is only supported under Unix, and some
1681 1686 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1682 1687 '+NUMBER' parameter necessary for this feature. Good editors like
1683 1688 (X)Emacs, vi, jed, pico and joe all do.
1684 1689
1685 1690 - If the argument is not found as a variable, IPython will look for a
1686 1691 file with that name (adding .py if necessary) and load it into the
1687 1692 editor. It will execute its contents with execfile() when you exit,
1688 1693 loading any code in the file into your interactive namespace.
1689 1694
1690 1695 After executing your code, %edit will return as output the code you
1691 1696 typed in the editor (except when it was an existing file). This way
1692 1697 you can reload the code in further invocations of %edit as a variable,
1693 1698 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1694 1699 the output.
1695 1700
1696 1701 Note that %edit is also available through the alias %ed.
1697 1702
1698 1703 This is an example of creating a simple function inside the editor and
1699 1704 then modifying it. First, start up the editor:
1700 1705
1701 1706 In [1]: ed\\
1702 1707 Editing... done. Executing edited code...\\
1703 1708 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1704 1709
1705 1710 We can then call the function foo():
1706 1711
1707 1712 In [2]: foo()\\
1708 1713 foo() was defined in an editing session
1709 1714
1710 1715 Now we edit foo. IPython automatically loads the editor with the
1711 1716 (temporary) file where foo() was previously defined:
1712 1717
1713 1718 In [3]: ed foo\\
1714 1719 Editing... done. Executing edited code...
1715 1720
1716 1721 And if we call foo() again we get the modified version:
1717 1722
1718 1723 In [4]: foo()\\
1719 1724 foo() has now been changed!
1720 1725
1721 1726 Here is an example of how to edit a code snippet successive
1722 1727 times. First we call the editor:
1723 1728
1724 1729 In [8]: ed\\
1725 1730 Editing... done. Executing edited code...\\
1726 1731 hello\\
1727 1732 Out[8]: "print 'hello'\\n"
1728 1733
1729 1734 Now we call it again with the previous output (stored in _):
1730 1735
1731 1736 In [9]: ed _\\
1732 1737 Editing... done. Executing edited code...\\
1733 1738 hello world\\
1734 1739 Out[9]: "print 'hello world'\\n"
1735 1740
1736 1741 Now we call it with the output #8 (stored in _8, also as Out[8]):
1737 1742
1738 1743 In [10]: ed _8\\
1739 1744 Editing... done. Executing edited code...\\
1740 1745 hello again\\
1741 1746 Out[10]: "print 'hello again'\\n"
1742 1747
1743 1748
1744 1749 Changing the default editor hook:
1745 1750
1746 1751 If you wish to write your own editor hook, you can put it in a
1747 1752 configuration file which you load at startup time. The default hook
1748 1753 is defined in the IPython.hooks module, and you can use that as a
1749 1754 starting example for further modifications. That file also has
1750 1755 general instructions on how to set a new hook for use once you've
1751 1756 defined it."""
1752 1757
1753 1758 # FIXME: This function has become a convoluted mess. It needs a
1754 1759 # ground-up rewrite with clean, simple logic.
1755 1760
1756 1761 def make_filename(arg):
1757 1762 "Make a filename from the given args"
1758 1763 try:
1759 1764 filename = get_py_filename(arg)
1760 1765 except IOError:
1761 1766 if args.endswith('.py'):
1762 1767 filename = arg
1763 1768 else:
1764 1769 filename = None
1765 1770 return filename
1766 1771
1767 1772 # custom exceptions
1768 1773 class DataIsObject(Exception): pass
1769 1774
1770 1775 opts,args = self.parse_options(parameter_s,'px')
1771 1776
1772 1777 # Default line number value
1773 1778 lineno = None
1774 1779 if opts.has_key('p'):
1775 1780 args = '_%s' % last_call[0]
1776 1781 if not self.shell.user_ns.has_key(args):
1777 1782 args = last_call[1]
1778 1783
1779 1784 # use last_call to remember the state of the previous call, but don't
1780 1785 # let it be clobbered by successive '-p' calls.
1781 1786 try:
1782 1787 last_call[0] = self.shell.outputcache.prompt_count
1783 1788 if not opts.has_key('p'):
1784 1789 last_call[1] = parameter_s
1785 1790 except:
1786 1791 pass
1787 1792
1788 1793 # by default this is done with temp files, except when the given
1789 1794 # arg is a filename
1790 1795 use_temp = 1
1791 1796
1792 1797 if re.match(r'\d',args):
1793 1798 # Mode where user specifies ranges of lines, like in %macro.
1794 1799 # This means that you can't edit files whose names begin with
1795 1800 # numbers this way. Tough.
1796 1801 ranges = args.split()
1797 1802 data = ''.join(self.extract_input_slices(ranges))
1798 1803 elif args.endswith('.py'):
1799 1804 filename = make_filename(args)
1800 1805 data = ''
1801 1806 use_temp = 0
1802 1807 elif args:
1803 1808 try:
1804 1809 # Load the parameter given as a variable. If not a string,
1805 1810 # process it as an object instead (below)
1806 1811
1807 1812 #print '*** args',args,'type',type(args) # dbg
1808 1813 data = eval(args,self.shell.user_ns)
1809 1814 if not type(data) in StringTypes:
1810 1815 raise DataIsObject
1811 1816 except (NameError,SyntaxError):
1812 1817 # given argument is not a variable, try as a filename
1813 1818 filename = make_filename(args)
1814 1819 if filename is None:
1815 1820 warn("Argument given (%s) can't be found as a variable "
1816 1821 "or as a filename." % args)
1817 1822 return
1818 1823 data = ''
1819 1824 use_temp = 0
1820 1825 except DataIsObject:
1821 1826 # For objects, try to edit the file where they are defined
1822 1827 try:
1823 1828 filename = inspect.getabsfile(data)
1824 1829 datafile = 1
1825 1830 except TypeError:
1826 1831 filename = make_filename(args)
1827 1832 datafile = 1
1828 1833 warn('Could not find file where `%s` is defined.\n'
1829 1834 'Opening a file named `%s`' % (args,filename))
1830 1835 # Now, make sure we can actually read the source (if it was in
1831 1836 # a temp file it's gone by now).
1832 1837 if datafile:
1833 1838 try:
1834 1839 lineno = inspect.getsourcelines(data)[1]
1835 1840 except IOError:
1836 1841 filename = make_filename(args)
1837 1842 if filename is None:
1838 1843 warn('The file `%s` where `%s` was defined cannot '
1839 1844 'be read.' % (filename,data))
1840 1845 return
1841 1846 use_temp = 0
1842 1847 else:
1843 1848 data = ''
1844 1849
1845 1850 if use_temp:
1846 1851 filename = tempfile.mktemp('.py')
1847 1852 self.shell.tempfiles.append(filename)
1848 1853
1849 1854 if data and use_temp:
1850 1855 tmp_file = open(filename,'w')
1851 1856 tmp_file.write(data)
1852 1857 tmp_file.close()
1853 1858
1854 1859 # do actual editing here
1855 1860 print 'Editing...',
1856 1861 sys.stdout.flush()
1857 1862 self.shell.hooks.editor(filename,lineno)
1858 1863 if opts.has_key('x'): # -x prevents actual execution
1859 1864 print
1860 1865 else:
1861 1866 print 'done. Executing edited code...'
1862 1867 try:
1863 1868 self.shell.safe_execfile(filename,self.shell.user_ns)
1864 1869 except IOError,msg:
1865 1870 if msg.filename == filename:
1866 1871 warn('File not found. Did you forget to save?')
1867 1872 return
1868 1873 else:
1869 1874 self.shell.showtraceback()
1870 1875 except:
1871 1876 self.shell.showtraceback()
1872 1877 if use_temp:
1873 1878 contents = open(filename).read()
1874 1879 return contents
1875 1880
1876 1881 def magic_xmode(self,parameter_s = ''):
1877 1882 """Switch modes for the exception handlers.
1878 1883
1879 1884 Valid modes: Plain, Context and Verbose.
1880 1885
1881 1886 If called without arguments, acts as a toggle."""
1882 1887
1883 1888 def xmode_switch_err(name):
1884 1889 warn('Error changing %s exception modes.\n%s' %
1885 1890 (name,sys.exc_info()[1]))
1886 1891
1887 1892 shell = self.shell
1888 1893 new_mode = parameter_s.strip().capitalize()
1889 1894 try:
1890 1895 shell.InteractiveTB.set_mode(mode=new_mode)
1891 1896 print 'Exception reporting mode:',shell.InteractiveTB.mode
1892 1897 except:
1893 1898 xmode_switch_err('user')
1894 1899
1895 1900 # threaded shells use a special handler in sys.excepthook
1896 1901 if shell.isthreaded:
1897 1902 try:
1898 1903 shell.sys_excepthook.set_mode(mode=new_mode)
1899 1904 except:
1900 1905 xmode_switch_err('threaded')
1901 1906
1902 1907 def magic_colors(self,parameter_s = ''):
1903 1908 """Switch color scheme for prompts, info system and exception handlers.
1904 1909
1905 1910 Currently implemented schemes: NoColor, Linux, LightBG.
1906 1911
1907 1912 Color scheme names are not case-sensitive."""
1908 1913
1909 1914 def color_switch_err(name):
1910 1915 warn('Error changing %s color schemes.\n%s' %
1911 1916 (name,sys.exc_info()[1]))
1912 1917
1913 1918
1914 1919 new_scheme = parameter_s.strip()
1915 1920 if not new_scheme:
1916 1921 print 'You must specify a color scheme.'
1917 1922 return
1918 1923 # Under Windows, check for Gary Bishop's readline, which is necessary
1919 1924 # for ANSI coloring
1920 1925 if os.name in ['nt','dos']:
1921 1926 try:
1922 1927 import readline
1923 1928 except ImportError:
1924 1929 has_readline = 0
1925 1930 else:
1926 1931 try:
1927 1932 readline.GetOutputFile()
1928 1933 except AttributeError:
1929 1934 has_readline = 0
1930 1935 else:
1931 1936 has_readline = 1
1932 1937 if not has_readline:
1933 1938 msg = """\
1934 1939 Proper color support under MS Windows requires Gary Bishop's readline library.
1935 1940 You can find it at:
1936 1941 http://sourceforge.net/projects/uncpythontools
1937 1942 Gary's readline needs the ctypes module, from:
1938 1943 http://starship.python.net/crew/theller/ctypes
1939 1944
1940 1945 Defaulting color scheme to 'NoColor'"""
1941 1946 new_scheme = 'NoColor'
1942 1947 warn(msg)
1943 1948 # local shortcut
1944 1949 shell = self.shell
1945 1950
1946 1951 # Set prompt colors
1947 1952 try:
1948 1953 shell.outputcache.set_colors(new_scheme)
1949 1954 except:
1950 1955 color_switch_err('prompt')
1951 1956 else:
1952 1957 shell.rc.colors = \
1953 1958 shell.outputcache.color_table.active_scheme_name
1954 1959 # Set exception colors
1955 1960 try:
1956 1961 shell.InteractiveTB.set_colors(scheme = new_scheme)
1957 1962 shell.SyntaxTB.set_colors(scheme = new_scheme)
1958 1963 except:
1959 1964 color_switch_err('exception')
1960 1965
1961 1966 # threaded shells use a verbose traceback in sys.excepthook
1962 1967 if shell.isthreaded:
1963 1968 try:
1964 1969 shell.sys_excepthook.set_colors(scheme=new_scheme)
1965 1970 except:
1966 1971 color_switch_err('system exception handler')
1967 1972
1968 1973 # Set info (for 'object?') colors
1969 1974 if shell.rc.color_info:
1970 1975 try:
1971 1976 shell.inspector.set_active_scheme(new_scheme)
1972 1977 except:
1973 1978 color_switch_err('object inspector')
1974 1979 else:
1975 1980 shell.inspector.set_active_scheme('NoColor')
1976 1981
1977 1982 def magic_color_info(self,parameter_s = ''):
1978 1983 """Toggle color_info.
1979 1984
1980 1985 The color_info configuration parameter controls whether colors are
1981 1986 used for displaying object details (by things like %psource, %pfile or
1982 1987 the '?' system). This function toggles this value with each call.
1983 1988
1984 1989 Note that unless you have a fairly recent pager (less works better
1985 1990 than more) in your system, using colored object information displays
1986 1991 will not work properly. Test it and see."""
1987 1992
1988 1993 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1989 1994 self.magic_colors(self.shell.rc.colors)
1990 1995 print 'Object introspection functions have now coloring:',
1991 1996 print ['OFF','ON'][self.shell.rc.color_info]
1992 1997
1993 1998 def magic_Pprint(self, parameter_s=''):
1994 1999 """Toggle pretty printing on/off."""
1995 2000
1996 2001 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1997 2002 print 'Pretty printing has been turned', \
1998 2003 ['OFF','ON'][self.shell.outputcache.Pprint]
1999 2004
2000 2005 def magic_exit(self, parameter_s=''):
2001 2006 """Exit IPython, confirming if configured to do so.
2002 2007
2003 2008 You can configure whether IPython asks for confirmation upon exit by
2004 2009 setting the confirm_exit flag in the ipythonrc file."""
2005 2010
2006 2011 self.shell.exit()
2007 2012
2008 2013 def magic_quit(self, parameter_s=''):
2009 2014 """Exit IPython, confirming if configured to do so (like %exit)"""
2010 2015
2011 2016 self.shell.exit()
2012 2017
2013 2018 def magic_Exit(self, parameter_s=''):
2014 2019 """Exit IPython without confirmation."""
2015 2020
2016 2021 self.shell.exit_now = True
2017 2022
2018 2023 def magic_Quit(self, parameter_s=''):
2019 2024 """Exit IPython without confirmation (like %Exit)."""
2020 2025
2021 2026 self.shell.exit_now = True
2022 2027
2023 2028 #......................................................................
2024 2029 # Functions to implement unix shell-type things
2025 2030
2026 2031 def magic_alias(self, parameter_s = ''):
2027 2032 """Define an alias for a system command.
2028 2033
2029 2034 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2030 2035
2031 2036 Then, typing 'alias_name params' will execute the system command 'cmd
2032 2037 params' (from your underlying operating system).
2033 2038
2034 2039 Aliases have lower precedence than magic functions and Python normal
2035 2040 variables, so if 'foo' is both a Python variable and an alias, the
2036 2041 alias can not be executed until 'del foo' removes the Python variable.
2037 2042
2038 2043 You can use the %l specifier in an alias definition to represent the
2039 2044 whole line when the alias is called. For example:
2040 2045
2041 2046 In [2]: alias all echo "Input in brackets: <%l>"\\
2042 2047 In [3]: all hello world\\
2043 2048 Input in brackets: <hello world>
2044 2049
2045 2050 You can also define aliases with parameters using %s specifiers (one
2046 2051 per parameter):
2047 2052
2048 2053 In [1]: alias parts echo first %s second %s\\
2049 2054 In [2]: %parts A B\\
2050 2055 first A second B\\
2051 2056 In [3]: %parts A\\
2052 2057 Incorrect number of arguments: 2 expected.\\
2053 2058 parts is an alias to: 'echo first %s second %s'
2054 2059
2055 2060 Note that %l and %s are mutually exclusive. You can only use one or
2056 2061 the other in your aliases.
2057 2062
2058 2063 Aliases expand Python variables just like system calls using ! or !!
2059 2064 do: all expressions prefixed with '$' get expanded. For details of
2060 2065 the semantic rules, see PEP-215:
2061 2066 http://www.python.org/peps/pep-0215.html. This is the library used by
2062 2067 IPython for variable expansion. If you want to access a true shell
2063 2068 variable, an extra $ is necessary to prevent its expansion by IPython:
2064 2069
2065 2070 In [6]: alias show echo\\
2066 2071 In [7]: PATH='A Python string'\\
2067 2072 In [8]: show $PATH\\
2068 2073 A Python string\\
2069 2074 In [9]: show $$PATH\\
2070 2075 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2071 2076
2072 2077 You can use the alias facility to acess all of $PATH. See the %rehash
2073 2078 and %rehashx functions, which automatically create aliases for the
2074 2079 contents of your $PATH.
2075 2080
2076 2081 If called with no parameters, %alias prints the current alias table."""
2077 2082
2078 2083 par = parameter_s.strip()
2079 2084 if not par:
2080 2085 if self.shell.rc.automagic:
2081 2086 prechar = ''
2082 2087 else:
2083 2088 prechar = self.shell.ESC_MAGIC
2084 2089 print 'Alias\t\tSystem Command\n'+'-'*30
2085 2090 atab = self.shell.alias_table
2086 2091 aliases = atab.keys()
2087 2092 aliases.sort()
2088 2093 for alias in aliases:
2089 2094 print prechar+alias+'\t\t'+atab[alias][1]
2090 2095 print '-'*30+'\nTotal number of aliases:',len(aliases)
2091 2096 return
2092 2097 try:
2093 2098 alias,cmd = par.split(None,1)
2094 2099 except:
2095 2100 print OInspect.getdoc(self.magic_alias)
2096 2101 else:
2097 2102 nargs = cmd.count('%s')
2098 2103 if nargs>0 and cmd.find('%l')>=0:
2099 2104 error('The %s and %l specifiers are mutually exclusive '
2100 2105 'in alias definitions.')
2101 2106 else: # all looks OK
2102 2107 self.shell.alias_table[alias] = (nargs,cmd)
2103 2108 self.shell.alias_table_validate(verbose=1)
2104 2109 # end magic_alias
2105 2110
2106 2111 def magic_unalias(self, parameter_s = ''):
2107 2112 """Remove an alias"""
2108 2113
2109 2114 aname = parameter_s.strip()
2110 2115 if aname in self.shell.alias_table:
2111 2116 del self.shell.alias_table[aname]
2112 2117
2113 2118 def magic_rehash(self, parameter_s = ''):
2114 2119 """Update the alias table with all entries in $PATH.
2115 2120
2116 2121 This version does no checks on execute permissions or whether the
2117 2122 contents of $PATH are truly files (instead of directories or something
2118 2123 else). For such a safer (but slower) version, use %rehashx."""
2119 2124
2120 2125 # This function (and rehashx) manipulate the alias_table directly
2121 2126 # rather than calling magic_alias, for speed reasons. A rehash on a
2122 2127 # typical Linux box involves several thousand entries, so efficiency
2123 2128 # here is a top concern.
2124 2129
2125 2130 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2126 2131 alias_table = self.shell.alias_table
2127 2132 for pdir in path:
2128 2133 for ff in os.listdir(pdir):
2129 2134 # each entry in the alias table must be (N,name), where
2130 2135 # N is the number of positional arguments of the alias.
2131 2136 alias_table[ff] = (0,ff)
2132 2137 # Make sure the alias table doesn't contain keywords or builtins
2133 2138 self.shell.alias_table_validate()
2134 2139 # Call again init_auto_alias() so we get 'rm -i' and other modified
2135 2140 # aliases since %rehash will probably clobber them
2136 2141 self.shell.init_auto_alias()
2137 2142
2138 2143 def magic_rehashx(self, parameter_s = ''):
2139 2144 """Update the alias table with all executable files in $PATH.
2140 2145
2141 2146 This version explicitly checks that every entry in $PATH is a file
2142 2147 with execute access (os.X_OK), so it is much slower than %rehash.
2143 2148
2144 2149 Under Windows, it checks executability as a match agains a
2145 2150 '|'-separated string of extensions, stored in the IPython config
2146 2151 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2147 2152
2148 2153 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2149 2154 alias_table = self.shell.alias_table
2150 2155
2151 2156 if os.name == 'posix':
2152 2157 isexec = lambda fname:os.path.isfile(fname) and \
2153 2158 os.access(fname,os.X_OK)
2154 2159 else:
2155 2160
2156 2161 try:
2157 2162 winext = os.environ['pathext'].replace(';','|').replace('.','')
2158 2163 except KeyError:
2159 2164 winext = 'exe|com|bat'
2160 2165
2161 2166 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2162 2167 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2163 2168 savedir = os.getcwd()
2164 2169 try:
2165 2170 # write the whole loop for posix/Windows so we don't have an if in
2166 2171 # the innermost part
2167 2172 if os.name == 'posix':
2168 2173 for pdir in path:
2169 2174 os.chdir(pdir)
2170 2175 for ff in os.listdir(pdir):
2171 2176 if isexec(ff):
2172 2177 # each entry in the alias table must be (N,name),
2173 2178 # where N is the number of positional arguments of the
2174 2179 # alias.
2175 2180 alias_table[ff] = (0,ff)
2176 2181 else:
2177 2182 for pdir in path:
2178 2183 os.chdir(pdir)
2179 2184 for ff in os.listdir(pdir):
2180 2185 if isexec(ff):
2181 2186 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2182 2187 # Make sure the alias table doesn't contain keywords or builtins
2183 2188 self.shell.alias_table_validate()
2184 2189 # Call again init_auto_alias() so we get 'rm -i' and other
2185 2190 # modified aliases since %rehashx will probably clobber them
2186 2191 self.shell.init_auto_alias()
2187 2192 finally:
2188 2193 os.chdir(savedir)
2189 2194
2190 2195 def magic_pwd(self, parameter_s = ''):
2191 2196 """Return the current working directory path."""
2192 2197 return os.getcwd()
2193 2198
2194 2199 def magic_cd(self, parameter_s=''):
2195 2200 """Change the current working directory.
2196 2201
2197 2202 This command automatically maintains an internal list of directories
2198 2203 you visit during your IPython session, in the variable _dh. The
2199 2204 command %dhist shows this history nicely formatted.
2200 2205
2201 2206 Usage:
2202 2207
2203 2208 cd 'dir': changes to directory 'dir'.
2204 2209
2205 2210 cd -: changes to the last visited directory.
2206 2211
2207 2212 cd -<n>: changes to the n-th directory in the directory history.
2208 2213
2209 2214 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2210 2215 (note: cd <bookmark_name> is enough if there is no
2211 2216 directory <bookmark_name>, but a bookmark with the name exists.)
2212 2217
2213 2218 Options:
2214 2219
2215 2220 -q: quiet. Do not print the working directory after the cd command is
2216 2221 executed. By default IPython's cd command does print this directory,
2217 2222 since the default prompts do not display path information.
2218 2223
2219 2224 Note that !cd doesn't work for this purpose because the shell where
2220 2225 !command runs is immediately discarded after executing 'command'."""
2221 2226
2222 2227 parameter_s = parameter_s.strip()
2223 2228 bkms = self.shell.persist.get("bookmarks",{})
2224 2229
2225 2230 numcd = re.match(r'(-)(\d+)$',parameter_s)
2226 2231 # jump in directory history by number
2227 2232 if numcd:
2228 2233 nn = int(numcd.group(2))
2229 2234 try:
2230 2235 ps = self.shell.user_ns['_dh'][nn]
2231 2236 except IndexError:
2232 2237 print 'The requested directory does not exist in history.'
2233 2238 return
2234 2239 else:
2235 2240 opts = {}
2236 2241 else:
2237 2242 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2238 2243 # jump to previous
2239 2244 if ps == '-':
2240 2245 try:
2241 2246 ps = self.shell.user_ns['_dh'][-2]
2242 2247 except IndexError:
2243 2248 print 'No previous directory to change to.'
2244 2249 return
2245 2250 # jump to bookmark
2246 2251 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2247 2252 if bkms.has_key(ps):
2248 2253 target = bkms[ps]
2249 2254 print '(bookmark:%s) -> %s' % (ps,target)
2250 2255 ps = target
2251 2256 else:
2252 2257 if bkms:
2253 2258 error("Bookmark '%s' not found. "
2254 2259 "Use '%bookmark -l' to see your bookmarks." % ps)
2255 2260 else:
2256 2261 print "Bookmarks not set - use %bookmark <bookmarkname>"
2257 2262 return
2258 2263
2259 2264 # at this point ps should point to the target dir
2260 2265 if ps:
2261 2266 try:
2262 2267 os.chdir(os.path.expanduser(ps))
2263 2268 except OSError:
2264 2269 print sys.exc_info()[1]
2265 2270 else:
2266 2271 self.shell.user_ns['_dh'].append(os.getcwd())
2267 2272 else:
2268 2273 os.chdir(self.shell.home_dir)
2269 2274 self.shell.user_ns['_dh'].append(os.getcwd())
2270 2275 if not 'q' in opts:
2271 2276 print self.shell.user_ns['_dh'][-1]
2272 2277
2273 2278 def magic_dhist(self, parameter_s=''):
2274 2279 """Print your history of visited directories.
2275 2280
2276 2281 %dhist -> print full history\\
2277 2282 %dhist n -> print last n entries only\\
2278 2283 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2279 2284
2280 2285 This history is automatically maintained by the %cd command, and
2281 2286 always available as the global list variable _dh. You can use %cd -<n>
2282 2287 to go to directory number <n>."""
2283 2288
2284 2289 dh = self.shell.user_ns['_dh']
2285 2290 if parameter_s:
2286 2291 try:
2287 2292 args = map(int,parameter_s.split())
2288 2293 except:
2289 2294 self.arg_err(Magic.magic_dhist)
2290 2295 return
2291 2296 if len(args) == 1:
2292 2297 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2293 2298 elif len(args) == 2:
2294 2299 ini,fin = args
2295 2300 else:
2296 2301 self.arg_err(Magic.magic_dhist)
2297 2302 return
2298 2303 else:
2299 2304 ini,fin = 0,len(dh)
2300 2305 nlprint(dh,
2301 2306 header = 'Directory history (kept in _dh)',
2302 2307 start=ini,stop=fin)
2303 2308
2304 2309 def magic_env(self, parameter_s=''):
2305 2310 """List environment variables."""
2306 2311
2307 2312 return os.environ.data
2308 2313
2309 2314 def magic_pushd(self, parameter_s=''):
2310 2315 """Place the current dir on stack and change directory.
2311 2316
2312 2317 Usage:\\
2313 2318 %pushd ['dirname']
2314 2319
2315 2320 %pushd with no arguments does a %pushd to your home directory.
2316 2321 """
2317 2322 if parameter_s == '': parameter_s = '~'
2318 2323 dir_s = self.shell.dir_stack
2319 2324 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2320 2325 os.path.expanduser(self.shell.dir_stack[0]):
2321 2326 try:
2322 2327 self.magic_cd(parameter_s)
2323 2328 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2324 2329 self.magic_dirs()
2325 2330 except:
2326 2331 print 'Invalid directory'
2327 2332 else:
2328 2333 print 'You are already there!'
2329 2334
2330 2335 def magic_popd(self, parameter_s=''):
2331 2336 """Change to directory popped off the top of the stack.
2332 2337 """
2333 2338 if len (self.shell.dir_stack) > 1:
2334 2339 self.shell.dir_stack.pop(0)
2335 2340 self.magic_cd(self.shell.dir_stack[0])
2336 2341 print self.shell.dir_stack[0]
2337 2342 else:
2338 2343 print "You can't remove the starting directory from the stack:",\
2339 2344 self.shell.dir_stack
2340 2345
2341 2346 def magic_dirs(self, parameter_s=''):
2342 2347 """Return the current directory stack."""
2343 2348
2344 2349 return self.shell.dir_stack[:]
2345 2350
2346 2351 def magic_sc(self, parameter_s=''):
2347 2352 """Shell capture - execute a shell command and capture its output.
2348 2353
2349 2354 %sc [options] varname=command
2350 2355
2351 2356 IPython will run the given command using commands.getoutput(), and
2352 2357 will then update the user's interactive namespace with a variable
2353 2358 called varname, containing the value of the call. Your command can
2354 2359 contain shell wildcards, pipes, etc.
2355 2360
2356 2361 The '=' sign in the syntax is mandatory, and the variable name you
2357 2362 supply must follow Python's standard conventions for valid names.
2358 2363
2359 2364 Options:
2360 2365
2361 2366 -l: list output. Split the output on newlines into a list before
2362 2367 assigning it to the given variable. By default the output is stored
2363 2368 as a single string.
2364 2369
2365 2370 -v: verbose. Print the contents of the variable.
2366 2371
2367 2372 In most cases you should not need to split as a list, because the
2368 2373 returned value is a special type of string which can automatically
2369 2374 provide its contents either as a list (split on newlines) or as a
2370 2375 space-separated string. These are convenient, respectively, either
2371 2376 for sequential processing or to be passed to a shell command.
2372 2377
2373 2378 For example:
2374 2379
2375 2380 # Capture into variable a
2376 2381 In [9]: sc a=ls *py
2377 2382
2378 2383 # a is a string with embedded newlines
2379 2384 In [10]: a
2380 2385 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2381 2386
2382 2387 # which can be seen as a list:
2383 2388 In [11]: a.l
2384 2389 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2385 2390
2386 2391 # or as a whitespace-separated string:
2387 2392 In [12]: a.s
2388 2393 Out[12]: 'setup.py win32_manual_post_install.py'
2389 2394
2390 2395 # a.s is useful to pass as a single command line:
2391 2396 In [13]: !wc -l $a.s
2392 2397 146 setup.py
2393 2398 130 win32_manual_post_install.py
2394 2399 276 total
2395 2400
2396 2401 # while the list form is useful to loop over:
2397 2402 In [14]: for f in a.l:
2398 2403 ....: !wc -l $f
2399 2404 ....:
2400 2405 146 setup.py
2401 2406 130 win32_manual_post_install.py
2402 2407
2403 2408 Similiarly, the lists returned by the -l option are also special, in
2404 2409 the sense that you can equally invoke the .s attribute on them to
2405 2410 automatically get a whitespace-separated string from their contents:
2406 2411
2407 2412 In [1]: sc -l b=ls *py
2408 2413
2409 2414 In [2]: b
2410 2415 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2411 2416
2412 2417 In [3]: b.s
2413 2418 Out[3]: 'setup.py win32_manual_post_install.py'
2414 2419
2415 2420 In summary, both the lists and strings used for ouptut capture have
2416 2421 the following special attributes:
2417 2422
2418 2423 .l (or .list) : value as list.
2419 2424 .n (or .nlstr): value as newline-separated string.
2420 2425 .s (or .spstr): value as space-separated string.
2421 2426 """
2422 2427
2423 2428 opts,args = self.parse_options(parameter_s,'lv')
2424 2429 # Try to get a variable name and command to run
2425 2430 try:
2426 2431 # the variable name must be obtained from the parse_options
2427 2432 # output, which uses shlex.split to strip options out.
2428 2433 var,_ = args.split('=',1)
2429 2434 var = var.strip()
2430 2435 # But the the command has to be extracted from the original input
2431 2436 # parameter_s, not on what parse_options returns, to avoid the
2432 2437 # quote stripping which shlex.split performs on it.
2433 2438 _,cmd = parameter_s.split('=',1)
2434 2439 except ValueError:
2435 2440 var,cmd = '',''
2436 2441 if not var:
2437 2442 error('you must specify a variable to assign the command to.')
2438 2443 return
2439 2444 # If all looks ok, proceed
2440 2445 out,err = self.shell.getoutputerror(cmd)
2441 2446 if err:
2442 2447 print >> Term.cerr,err
2443 2448 if opts.has_key('l'):
2444 2449 out = SList(out.split('\n'))
2445 2450 else:
2446 2451 out = LSString(out)
2447 2452 if opts.has_key('v'):
2448 2453 print '%s ==\n%s' % (var,pformat(out))
2449 2454 self.shell.user_ns.update({var:out})
2450 2455
2451 2456 def magic_sx(self, parameter_s=''):
2452 2457 """Shell execute - run a shell command and capture its output.
2453 2458
2454 2459 %sx command
2455 2460
2456 2461 IPython will run the given command using commands.getoutput(), and
2457 2462 return the result formatted as a list (split on '\\n'). Since the
2458 2463 output is _returned_, it will be stored in ipython's regular output
2459 2464 cache Out[N] and in the '_N' automatic variables.
2460 2465
2461 2466 Notes:
2462 2467
2463 2468 1) If an input line begins with '!!', then %sx is automatically
2464 2469 invoked. That is, while:
2465 2470 !ls
2466 2471 causes ipython to simply issue system('ls'), typing
2467 2472 !!ls
2468 2473 is a shorthand equivalent to:
2469 2474 %sx ls
2470 2475
2471 2476 2) %sx differs from %sc in that %sx automatically splits into a list,
2472 2477 like '%sc -l'. The reason for this is to make it as easy as possible
2473 2478 to process line-oriented shell output via further python commands.
2474 2479 %sc is meant to provide much finer control, but requires more
2475 2480 typing.
2476 2481
2477 2482 3) Just like %sc -l, this is a list with special attributes:
2478 2483
2479 2484 .l (or .list) : value as list.
2480 2485 .n (or .nlstr): value as newline-separated string.
2481 2486 .s (or .spstr): value as whitespace-separated string.
2482 2487
2483 2488 This is very useful when trying to use such lists as arguments to
2484 2489 system commands."""
2485 2490
2486 2491 if parameter_s:
2487 2492 out,err = self.shell.getoutputerror(parameter_s)
2488 2493 if err:
2489 2494 print >> Term.cerr,err
2490 2495 return SList(out.split('\n'))
2491 2496
2492 2497 def magic_bg(self, parameter_s=''):
2493 2498 """Run a job in the background, in a separate thread.
2494 2499
2495 2500 For example,
2496 2501
2497 2502 %bg myfunc(x,y,z=1)
2498 2503
2499 2504 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2500 2505 execution starts, a message will be printed indicating the job
2501 2506 number. If your job number is 5, you can use
2502 2507
2503 2508 myvar = jobs.result(5) or myvar = jobs[5].result
2504 2509
2505 2510 to assign this result to variable 'myvar'.
2506 2511
2507 2512 IPython has a job manager, accessible via the 'jobs' object. You can
2508 2513 type jobs? to get more information about it, and use jobs.<TAB> to see
2509 2514 its attributes. All attributes not starting with an underscore are
2510 2515 meant for public use.
2511 2516
2512 2517 In particular, look at the jobs.new() method, which is used to create
2513 2518 new jobs. This magic %bg function is just a convenience wrapper
2514 2519 around jobs.new(), for expression-based jobs. If you want to create a
2515 2520 new job with an explicit function object and arguments, you must call
2516 2521 jobs.new() directly.
2517 2522
2518 2523 The jobs.new docstring also describes in detail several important
2519 2524 caveats associated with a thread-based model for background job
2520 2525 execution. Type jobs.new? for details.
2521 2526
2522 2527 You can check the status of all jobs with jobs.status().
2523 2528
2524 2529 The jobs variable is set by IPython into the Python builtin namespace.
2525 2530 If you ever declare a variable named 'jobs', you will shadow this
2526 2531 name. You can either delete your global jobs variable to regain
2527 2532 access to the job manager, or make a new name and assign it manually
2528 2533 to the manager (stored in IPython's namespace). For example, to
2529 2534 assign the job manager to the Jobs name, use:
2530 2535
2531 2536 Jobs = __builtins__.jobs"""
2532 2537
2533 2538 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2534 2539
2535 2540 def magic_store(self, parameter_s=''):
2536 2541 """Lightweight persistence for python variables.
2537 2542
2538 2543 Example:
2539 2544
2540 2545 ville@badger[~]|1> A = ['hello',10,'world']\\
2541 2546 ville@badger[~]|2> %store A\\
2542 2547 ville@badger[~]|3> Exit
2543 2548
2544 2549 (IPython session is closed and started again...)
2545 2550
2546 2551 ville@badger:~$ ipython -p pysh\\
2547 2552 ville@badger[~]|1> print A
2548 2553
2549 2554 ['hello', 10, 'world']
2550 2555
2551 2556 Usage:
2552 2557
2553 2558 %store - Show list of all variables and their current values\\
2554 2559 %store <var> - Store the *current* value of the variable to disk\\
2555 2560 %store -d - Remove the variable and its value from storage\\
2556 2561 %store -r - Remove all variables from storage
2557 2562
2558 2563 It should be noted that if you change the value of a variable, you
2559 2564 need to %store it again if you want to persist the new value.
2560 2565
2561 2566 Note also that the variables will need to be pickleable; most basic
2562 2567 python types can be safely %stored.
2563 2568 """
2564 2569
2565 2570 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2566 2571 # delete
2567 2572 if opts.has_key('d'):
2568 2573 try:
2569 2574 todel = args[0]
2570 2575 except IndexError:
2571 2576 error('You must provide the variable to forget')
2572 2577 else:
2573 2578 try:
2574 2579 del self.shell.persist['S:' + todel]
2575 2580 except:
2576 2581 error("Can't delete variable '%s'" % todel)
2577 2582 # reset
2578 2583 elif opts.has_key('r'):
2579 2584 for k in self.shell.persist.keys():
2580 2585 if k.startswith('S:'):
2581 2586 del self.shell.persist[k]
2582 2587
2583 2588 # run without arguments -> list variables & values
2584 2589 elif not args:
2585 2590 vars = [v[2:] for v in self.shell.persist.keys()
2586 2591 if v.startswith('S:')]
2587 2592 vars.sort()
2588 2593 if vars:
2589 2594 size = max(map(len,vars))
2590 2595 else:
2591 2596 size = 0
2592 2597
2593 2598 print 'Stored variables and their in-memory values:'
2594 2599 fmt = '%-'+str(size)+'s -> %s'
2595 2600 get = self.shell.user_ns.get
2596 2601 for var in vars:
2597 2602 # print 30 first characters from every var
2598 2603 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2599 2604
2600 2605 # default action - store the variable
2601 2606 else:
2602 2607 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2603 2608 self.shell.persist[ 'S:' + args[0] ] = pickled
2604 2609 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2605 2610
2606 2611 def magic_bookmark(self, parameter_s=''):
2607 2612 """Manage IPython's bookmark system.
2608 2613
2609 2614 %bookmark <name> - set bookmark to current dir
2610 2615 %bookmark <name> <dir> - set bookmark to <dir>
2611 2616 %bookmark -l - list all bookmarks
2612 2617 %bookmark -d <name> - remove bookmark
2613 2618 %bookmark -r - remove all bookmarks
2614 2619
2615 2620 You can later on access a bookmarked folder with:
2616 2621 %cd -b <name>
2617 2622 or simply '%cd <name>' if there is no directory called <name> AND
2618 2623 there is such a bookmark defined.
2619 2624
2620 2625 Your bookmarks persist through IPython sessions, but they are
2621 2626 associated with each profile."""
2622 2627
2623 2628 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2624 2629 if len(args) > 2:
2625 2630 error('You can only give at most two arguments')
2626 2631 return
2627 2632
2628 2633 bkms = self.shell.persist.get('bookmarks',{})
2629 2634
2630 2635 if opts.has_key('d'):
2631 2636 try:
2632 2637 todel = args[0]
2633 2638 except IndexError:
2634 2639 error('You must provide a bookmark to delete')
2635 2640 else:
2636 2641 try:
2637 2642 del bkms[todel]
2638 2643 except:
2639 2644 error("Can't delete bookmark '%s'" % todel)
2640 2645 elif opts.has_key('r'):
2641 2646 bkms = {}
2642 2647 elif opts.has_key('l'):
2643 2648 bks = bkms.keys()
2644 2649 bks.sort()
2645 2650 if bks:
2646 2651 size = max(map(len,bks))
2647 2652 else:
2648 2653 size = 0
2649 2654 fmt = '%-'+str(size)+'s -> %s'
2650 2655 print 'Current bookmarks:'
2651 2656 for bk in bks:
2652 2657 print fmt % (bk,bkms[bk])
2653 2658 else:
2654 2659 if not args:
2655 2660 error("You must specify the bookmark name")
2656 2661 elif len(args)==1:
2657 2662 bkms[args[0]] = os.getcwd()
2658 2663 elif len(args)==2:
2659 2664 bkms[args[0]] = args[1]
2660 2665 self.shell.persist['bookmarks'] = bkms
2661 2666
2662 2667 def magic_pycat(self, parameter_s=''):
2663 2668 """Show a syntax-highlighted file through a pager.
2664 2669
2665 2670 This magic is similar to the cat utility, but it will assume the file
2666 2671 to be Python source and will show it with syntax highlighting. """
2667 2672
2668 2673 filename = get_py_filename(parameter_s)
2669 2674 page(self.shell.colorize(file_read(filename)),
2670 2675 screen_lines=self.shell.rc.screen_length)
2671 2676
2672 2677 # end Magic
@@ -1,76 +1,76 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Release data for the IPython project.
3 3
4 $Id: Release.py 982 2005-12-30 23:57:07Z fperez $"""
4 $Id: Release.py 984 2005-12-31 08:40:31Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 10 # <n8gray@caltech.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 # Name of the package for release purposes. This is the name which labels
17 17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 18 name = 'ipython'
19 19
20 20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 21 # the new substring. We have to avoid using either dashes or underscores,
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25 version = '0.7.0.rc3'
25 version = '0.7.0.rc4'
26 26
27 revision = '$Revision: 982 $'
27 revision = '$Revision: 984 $'
28 28
29 29 description = "An enhanced interactive Python shell."
30 30
31 31 long_description = \
32 32 """
33 33 IPython provides a replacement for the interactive Python interpreter with
34 34 extra functionality.
35 35
36 36 Main features:
37 37
38 38 * Comprehensive object introspection.
39 39
40 40 * Input history, persistent across sessions.
41 41
42 42 * Caching of output results during a session with automatically generated
43 43 references.
44 44
45 45 * Readline based name completion.
46 46
47 47 * Extensible system of 'magic' commands for controlling the environment and
48 48 performing many tasks related either to IPython or the operating system.
49 49
50 50 * Configuration system with easy switching between different setups (simpler
51 51 than changing $PYTHONSTARTUP environment variables every time).
52 52
53 53 * Session logging and reloading.
54 54
55 55 * Extensible syntax processing for special purpose situations.
56 56
57 57 * Access to the system shell with user-extensible alias system.
58 58
59 59 * Easily embeddable in other Python programs.
60 60
61 61 * Integrated access to the pdb debugger and the Python profiler. """
62 62
63 63 license = 'BSD'
64 64
65 65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu')
68 68 }
69 69
70 70 url = 'http://ipython.scipy.org'
71 71
72 72 download_url = 'http://ipython.scipy.org/dist'
73 73
74 74 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
75 75
76 76 keywords = ['Interactive','Interpreter','Shell']
@@ -1,2060 +1,2058 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 983 2005-12-31 00:04:25Z fperez $
9 $Id: iplib.py 984 2005-12-31 08:40:31Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import traceback
59 59 import types
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.Struct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76
77 77 # store the builtin raw_input globally, and use this always, in case user code
78 78 # overwrites it (like wx.py.PyShell does)
79 79 raw_input_original = raw_input
80 80
81 81 # compiled regexps for autoindent management
82 82 ini_spaces_re = re.compile(r'^(\s+)')
83 83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84 84
85 85 #****************************************************************************
86 86 # Some utility function definitions
87 87
88 88 def softspace(file, newvalue):
89 89 """Copied from code.py, to remove the dependency"""
90 90 oldvalue = 0
91 91 try:
92 92 oldvalue = file.softspace
93 93 except AttributeError:
94 94 pass
95 95 try:
96 96 file.softspace = newvalue
97 97 except (AttributeError, TypeError):
98 98 # "attribute-less object" or "read-only attributes"
99 99 pass
100 100 return oldvalue
101 101
102 102 #****************************************************************************
103 103 # These special functions get installed in the builtin namespace, to provide
104 104 # programmatic (pure python) access to magics, aliases and system calls. This
105 105 # is important for logging, user scripting, and more.
106 106
107 107 # We are basically exposing, via normal python functions, the three mechanisms
108 108 # in which ipython offers special call modes (magics for internal control,
109 109 # aliases for direct system access via pre-selected names, and !cmd for
110 110 # calling arbitrary system commands).
111 111
112 112 def ipmagic(arg_s):
113 113 """Call a magic function by name.
114 114
115 115 Input: a string containing the name of the magic function to call and any
116 116 additional arguments to be passed to the magic.
117 117
118 118 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
119 119 prompt:
120 120
121 121 In[1]: %name -opt foo bar
122 122
123 123 To call a magic without arguments, simply use ipmagic('name').
124 124
125 125 This provides a proper Python function to call IPython's magics in any
126 126 valid Python code you can type at the interpreter, including loops and
127 127 compound statements. It is added by IPython to the Python builtin
128 128 namespace upon initialization."""
129 129
130 130 args = arg_s.split(' ',1)
131 131 magic_name = args[0]
132 132 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
133 133 magic_name = magic_name[1:]
134 134 try:
135 135 magic_args = args[1]
136 136 except IndexError:
137 137 magic_args = ''
138 138 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
139 139 if fn is None:
140 140 error("Magic function `%s` not found." % magic_name)
141 141 else:
142 142 magic_args = __IPYTHON__.var_expand(magic_args)
143 143 return fn(magic_args)
144 144
145 145 def ipalias(arg_s):
146 146 """Call an alias by name.
147 147
148 148 Input: a string containing the name of the alias to call and any
149 149 additional arguments to be passed to the magic.
150 150
151 151 ipalias('name -opt foo bar') is equivalent to typing at the ipython
152 152 prompt:
153 153
154 154 In[1]: name -opt foo bar
155 155
156 156 To call an alias without arguments, simply use ipalias('name').
157 157
158 158 This provides a proper Python function to call IPython's aliases in any
159 159 valid Python code you can type at the interpreter, including loops and
160 160 compound statements. It is added by IPython to the Python builtin
161 161 namespace upon initialization."""
162 162
163 163 args = arg_s.split(' ',1)
164 164 alias_name = args[0]
165 165 try:
166 166 alias_args = args[1]
167 167 except IndexError:
168 168 alias_args = ''
169 169 if alias_name in __IPYTHON__.alias_table:
170 170 __IPYTHON__.call_alias(alias_name,alias_args)
171 171 else:
172 172 error("Alias `%s` not found." % alias_name)
173 173
174 174 def ipsystem(arg_s):
175 175 """Make a system call, using IPython."""
176 176 __IPYTHON__.system(arg_s)
177 177
178 178
179 179 #****************************************************************************
180 180 # Local use exceptions
181 181 class SpaceInInput(exceptions.Exception): pass
182 182
183 183 #****************************************************************************
184 184 # Local use classes
185 185 class Bunch: pass
186 186
187 187 class InputList(list):
188 188 """Class to store user input.
189 189
190 190 It's basically a list, but slices return a string instead of a list, thus
191 191 allowing things like (assuming 'In' is an instance):
192 192
193 193 exec In[4:7]
194 194
195 195 or
196 196
197 197 exec In[5:9] + In[14] + In[21:25]"""
198 198
199 199 def __getslice__(self,i,j):
200 200 return ''.join(list.__getslice__(self,i,j))
201 201
202 202 class SyntaxTB(ultraTB.ListTB):
203 203 """Extension which holds some state: the last exception value"""
204 204
205 205 def __init__(self,color_scheme = 'NoColor'):
206 206 ultraTB.ListTB.__init__(self,color_scheme)
207 207 self.last_syntax_error = None
208 208
209 209 def __call__(self, etype, value, elist):
210 210 self.last_syntax_error = value
211 211 ultraTB.ListTB.__call__(self,etype,value,elist)
212 212
213 213 def clear_err_state(self):
214 214 """Return the current error state and clear it"""
215 215 e = self.last_syntax_error
216 216 self.last_syntax_error = None
217 217 return e
218 218
219 219 #****************************************************************************
220 220 # Main IPython class
221 221
222 222 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
223 223 # until a full rewrite is made. I've cleaned all cross-class uses of
224 224 # attributes and methods, but too much user code out there relies on the
225 225 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
226 226 #
227 227 # But at least now, all the pieces have been separated and we could, in
228 228 # principle, stop using the mixin. This will ease the transition to the
229 229 # chainsaw branch.
230 230
231 231 # For reference, the following is the list of 'self.foo' uses in the Magic
232 232 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
233 233 # class, to prevent clashes.
234 234
235 235 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
236 236 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
237 237 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
238 238 # 'self.value']
239 239
240 class InteractiveShell(Magic):
240 class InteractiveShell(object,Magic):
241 241 """An enhanced console for Python."""
242 242
243 243 # class attribute to indicate whether the class supports threads or not.
244 244 # Subclasses with thread support should override this as needed.
245 245 isthreaded = False
246 246
247 247 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
248 248 user_ns = None,user_global_ns=None,banner2='',
249 249 custom_exceptions=((),None),embedded=False):
250 250
251 251 # some minimal strict typechecks. For some core data structures, I
252 252 # want actual basic python types, not just anything that looks like
253 253 # one. This is especially true for namespaces.
254 254 for ns in (user_ns,user_global_ns):
255 255 if ns is not None and type(ns) != types.DictType:
256 256 raise TypeError,'namespace must be a dictionary'
257 257
258 258 # Put a reference to self in builtins so that any form of embedded or
259 259 # imported code can test for being inside IPython.
260 260 __builtin__.__IPYTHON__ = self
261 261
262 262 # And load into builtins ipmagic/ipalias/ipsystem as well
263 263 __builtin__.ipmagic = ipmagic
264 264 __builtin__.ipalias = ipalias
265 265 __builtin__.ipsystem = ipsystem
266 266
267 267 # Add to __builtin__ other parts of IPython's public API
268 268 __builtin__.ip_set_hook = self.set_hook
269 269
270 270 # Keep in the builtins a flag for when IPython is active. We set it
271 271 # with setdefault so that multiple nested IPythons don't clobber one
272 272 # another. Each will increase its value by one upon being activated,
273 273 # which also gives us a way to determine the nesting level.
274 274 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
275 275
276 276 # Do the intuitively correct thing for quit/exit: we remove the
277 277 # builtins if they exist, and our own prefilter routine will handle
278 278 # these special cases
279 279 try:
280 280 del __builtin__.exit, __builtin__.quit
281 281 except AttributeError:
282 282 pass
283 283
284 284 # Store the actual shell's name
285 285 self.name = name
286 286
287 287 # We need to know whether the instance is meant for embedding, since
288 288 # global/local namespaces need to be handled differently in that case
289 289 self.embedded = embedded
290 290
291 291 # command compiler
292 292 self.compile = codeop.CommandCompiler()
293 293
294 294 # User input buffer
295 295 self.buffer = []
296 296
297 297 # Default name given in compilation of code
298 298 self.filename = '<ipython console>'
299 299
300 300 # Create the namespace where the user will operate. user_ns is
301 301 # normally the only one used, and it is passed to the exec calls as
302 302 # the locals argument. But we do carry a user_global_ns namespace
303 303 # given as the exec 'globals' argument, This is useful in embedding
304 304 # situations where the ipython shell opens in a context where the
305 305 # distinction between locals and globals is meaningful.
306 306
307 307 # FIXME. For some strange reason, __builtins__ is showing up at user
308 308 # level as a dict instead of a module. This is a manual fix, but I
309 309 # should really track down where the problem is coming from. Alex
310 310 # Schmolck reported this problem first.
311 311
312 312 # A useful post by Alex Martelli on this topic:
313 313 # Re: inconsistent value from __builtins__
314 314 # Von: Alex Martelli <aleaxit@yahoo.com>
315 315 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
316 316 # Gruppen: comp.lang.python
317 317
318 318 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
319 319 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
320 320 # > <type 'dict'>
321 321 # > >>> print type(__builtins__)
322 322 # > <type 'module'>
323 323 # > Is this difference in return value intentional?
324 324
325 325 # Well, it's documented that '__builtins__' can be either a dictionary
326 326 # or a module, and it's been that way for a long time. Whether it's
327 327 # intentional (or sensible), I don't know. In any case, the idea is
328 328 # that if you need to access the built-in namespace directly, you
329 329 # should start with "import __builtin__" (note, no 's') which will
330 330 # definitely give you a module. Yeah, it's somewhat confusing:-(.
331 331
332 332 if user_ns is None:
333 333 # Set __name__ to __main__ to better match the behavior of the
334 334 # normal interpreter.
335 335 user_ns = {'__name__' :'__main__',
336 336 '__builtins__' : __builtin__,
337 337 }
338 338
339 339 if user_global_ns is None:
340 340 user_global_ns = {}
341 341
342 342 # Assign namespaces
343 343 # This is the namespace where all normal user variables live
344 344 self.user_ns = user_ns
345 345 # Embedded instances require a separate namespace for globals.
346 346 # Normally this one is unused by non-embedded instances.
347 347 self.user_global_ns = user_global_ns
348 348 # A namespace to keep track of internal data structures to prevent
349 349 # them from cluttering user-visible stuff. Will be updated later
350 350 self.internal_ns = {}
351 351
352 352 # Namespace of system aliases. Each entry in the alias
353 353 # table must be a 2-tuple of the form (N,name), where N is the number
354 354 # of positional arguments of the alias.
355 355 self.alias_table = {}
356 356
357 357 # A table holding all the namespaces IPython deals with, so that
358 358 # introspection facilities can search easily.
359 359 self.ns_table = {'user':user_ns,
360 360 'user_global':user_global_ns,
361 361 'alias':self.alias_table,
362 362 'internal':self.internal_ns,
363 363 'builtin':__builtin__.__dict__
364 364 }
365 365
366 366 # The user namespace MUST have a pointer to the shell itself.
367 367 self.user_ns[name] = self
368 368
369 369 # We need to insert into sys.modules something that looks like a
370 370 # module but which accesses the IPython namespace, for shelve and
371 371 # pickle to work interactively. Normally they rely on getting
372 372 # everything out of __main__, but for embedding purposes each IPython
373 373 # instance has its own private namespace, so we can't go shoving
374 374 # everything into __main__.
375 375
376 376 # note, however, that we should only do this for non-embedded
377 377 # ipythons, which really mimic the __main__.__dict__ with their own
378 378 # namespace. Embedded instances, on the other hand, should not do
379 379 # this because they need to manage the user local/global namespaces
380 380 # only, but they live within a 'normal' __main__ (meaning, they
381 381 # shouldn't overtake the execution environment of the script they're
382 382 # embedded in).
383 383
384 384 if not embedded:
385 385 try:
386 386 main_name = self.user_ns['__name__']
387 387 except KeyError:
388 388 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
389 389 else:
390 390 #print "pickle hack in place" # dbg
391 #print 'main_name:',main_name # dbg
391 392 sys.modules[main_name] = FakeModule(self.user_ns)
392 393
393 394 # List of input with multi-line handling.
394 395 # Fill its zero entry, user counter starts at 1
395 396 self.input_hist = InputList(['\n'])
396 397
397 398 # list of visited directories
398 399 try:
399 400 self.dir_hist = [os.getcwd()]
400 401 except IOError, e:
401 402 self.dir_hist = []
402 403
403 404 # dict of output history
404 405 self.output_hist = {}
405 406
406 407 # dict of things NOT to alias (keywords, builtins and some magics)
407 408 no_alias = {}
408 409 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
409 410 for key in keyword.kwlist + no_alias_magics:
410 411 no_alias[key] = 1
411 412 no_alias.update(__builtin__.__dict__)
412 413 self.no_alias = no_alias
413 414
414 415 # make global variables for user access to these
415 416 self.user_ns['_ih'] = self.input_hist
416 417 self.user_ns['_oh'] = self.output_hist
417 418 self.user_ns['_dh'] = self.dir_hist
418 419
419 420 # user aliases to input and output histories
420 421 self.user_ns['In'] = self.input_hist
421 422 self.user_ns['Out'] = self.output_hist
422 423
423 424 # Object variable to store code object waiting execution. This is
424 425 # used mainly by the multithreaded shells, but it can come in handy in
425 426 # other situations. No need to use a Queue here, since it's a single
426 427 # item which gets cleared once run.
427 428 self.code_to_run = None
428 429
429 430 # Job manager (for jobs run as background threads)
430 431 self.jobs = BackgroundJobManager()
431 432 # Put the job manager into builtins so it's always there.
432 433 __builtin__.jobs = self.jobs
433 434
434 435 # escapes for automatic behavior on the command line
435 436 self.ESC_SHELL = '!'
436 437 self.ESC_HELP = '?'
437 438 self.ESC_MAGIC = '%'
438 439 self.ESC_QUOTE = ','
439 440 self.ESC_QUOTE2 = ';'
440 441 self.ESC_PAREN = '/'
441 442
442 443 # And their associated handlers
443 444 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
444 445 self.ESC_QUOTE : self.handle_auto,
445 446 self.ESC_QUOTE2 : self.handle_auto,
446 447 self.ESC_MAGIC : self.handle_magic,
447 448 self.ESC_HELP : self.handle_help,
448 449 self.ESC_SHELL : self.handle_shell_escape,
449 450 }
450 451
451 452 # class initializations
452 453 Magic.__init__(self,self)
453 454
454 455 # Python source parser/formatter for syntax highlighting
455 456 pyformat = PyColorize.Parser().format
456 457 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
457 458
458 459 # hooks holds pointers used for user-side customizations
459 460 self.hooks = Struct()
460 461
461 462 # Set all default hooks, defined in the IPython.hooks module.
462 463 hooks = IPython.hooks
463 464 for hook_name in hooks.__all__:
464 465 self.set_hook(hook_name,getattr(hooks,hook_name))
465 466
466 467 # Flag to mark unconditional exit
467 468 self.exit_now = False
468 469
469 470 self.usage_min = """\
470 471 An enhanced console for Python.
471 472 Some of its features are:
472 473 - Readline support if the readline library is present.
473 474 - Tab completion in the local namespace.
474 475 - Logging of input, see command-line options.
475 476 - System shell escape via ! , eg !ls.
476 477 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
477 478 - Keeps track of locally defined variables via %who, %whos.
478 479 - Show object information with a ? eg ?x or x? (use ?? for more info).
479 480 """
480 481 if usage: self.usage = usage
481 482 else: self.usage = self.usage_min
482 483
483 484 # Storage
484 485 self.rc = rc # This will hold all configuration information
485 486 self.pager = 'less'
486 487 # temporary files used for various purposes. Deleted at exit.
487 488 self.tempfiles = []
488 489
489 490 # Keep track of readline usage (later set by init_readline)
490 491 self.has_readline = False
491 492
492 493 # template for logfile headers. It gets resolved at runtime by the
493 494 # logstart method.
494 495 self.loghead_tpl = \
495 496 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
496 497 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
497 498 #log# opts = %s
498 499 #log# args = %s
499 500 #log# It is safe to make manual edits below here.
500 501 #log#-----------------------------------------------------------------------
501 502 """
502 503 # for pushd/popd management
503 504 try:
504 505 self.home_dir = get_home_dir()
505 506 except HomeDirError,msg:
506 507 fatal(msg)
507 508
508 509 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
509 510
510 511 # Functions to call the underlying shell.
511 512
512 513 # utility to expand user variables via Itpl
513 514 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
514 515 self.user_ns))
515 516 # The first is similar to os.system, but it doesn't return a value,
516 517 # and it allows interpolation of variables in the user's namespace.
517 518 self.system = lambda cmd: shell(self.var_expand(cmd),
518 519 header='IPython system call: ',
519 520 verbose=self.rc.system_verbose)
520 521 # These are for getoutput and getoutputerror:
521 522 self.getoutput = lambda cmd: \
522 523 getoutput(self.var_expand(cmd),
523 524 header='IPython system call: ',
524 525 verbose=self.rc.system_verbose)
525 526 self.getoutputerror = lambda cmd: \
526 527 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
527 528 self.user_ns)),
528 529 header='IPython system call: ',
529 530 verbose=self.rc.system_verbose)
530 531
531 532 # RegExp for splitting line contents into pre-char//first
532 533 # word-method//rest. For clarity, each group in on one line.
533 534
534 535 # WARNING: update the regexp if the above escapes are changed, as they
535 536 # are hardwired in.
536 537
537 538 # Don't get carried away with trying to make the autocalling catch too
538 539 # much: it's better to be conservative rather than to trigger hidden
539 540 # evals() somewhere and end up causing side effects.
540 541
541 542 self.line_split = re.compile(r'^([\s*,;/])'
542 543 r'([\?\w\.]+\w*\s*)'
543 544 r'(\(?.*$)')
544 545
545 546 # Original re, keep around for a while in case changes break something
546 547 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
547 548 # r'(\s*[\?\w\.]+\w*\s*)'
548 549 # r'(\(?.*$)')
549 550
550 551 # RegExp to identify potential function names
551 552 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
552 553 # RegExp to exclude strings with this start from autocalling
553 554 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
554 555
555 556 # try to catch also methods for stuff in lists/tuples/dicts: off
556 557 # (experimental). For this to work, the line_split regexp would need
557 558 # to be modified so it wouldn't break things at '['. That line is
558 559 # nasty enough that I shouldn't change it until I can test it _well_.
559 560 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
560 561
561 562 # keep track of where we started running (mainly for crash post-mortem)
562 563 self.starting_dir = os.getcwd()
563 564
564 565 # Various switches which can be set
565 566 self.CACHELENGTH = 5000 # this is cheap, it's just text
566 567 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
567 568 self.banner2 = banner2
568 569
569 570 # TraceBack handlers:
570 571
571 572 # Syntax error handler.
572 573 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
573 574
574 575 # The interactive one is initialized with an offset, meaning we always
575 576 # want to remove the topmost item in the traceback, which is our own
576 577 # internal code. Valid modes: ['Plain','Context','Verbose']
577 578 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
578 579 color_scheme='NoColor',
579 580 tb_offset = 1)
580 581
581 582 # IPython itself shouldn't crash. This will produce a detailed
582 583 # post-mortem if it does. But we only install the crash handler for
583 584 # non-threaded shells, the threaded ones use a normal verbose reporter
584 585 # and lose the crash handler. This is because exceptions in the main
585 586 # thread (such as in GUI code) propagate directly to sys.excepthook,
586 587 # and there's no point in printing crash dumps for every user exception.
587 588 if self.isthreaded:
588 589 sys.excepthook = ultraTB.FormattedTB()
589 590 else:
590 591 from IPython import CrashHandler
591 592 sys.excepthook = CrashHandler.CrashHandler(self)
592 593
593 594 # The instance will store a pointer to this, so that runtime code
594 595 # (such as magics) can access it. This is because during the
595 596 # read-eval loop, it gets temporarily overwritten (to deal with GUI
596 597 # frameworks).
597 598 self.sys_excepthook = sys.excepthook
598 599
599 600 # and add any custom exception handlers the user may have specified
600 601 self.set_custom_exc(*custom_exceptions)
601 602
602 603 # Object inspector
603 604 self.inspector = OInspect.Inspector(OInspect.InspectColors,
604 605 PyColorize.ANSICodeColors,
605 606 'NoColor')
606 607 # indentation management
607 608 self.autoindent = False
608 609 self.indent_current_nsp = 0
609 610 self.indent_current = '' # actual indent string
610 611
611 612 # Make some aliases automatically
612 613 # Prepare list of shell aliases to auto-define
613 614 if os.name == 'posix':
614 615 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
615 616 'mv mv -i','rm rm -i','cp cp -i',
616 617 'cat cat','less less','clear clear',
617 618 # a better ls
618 619 'ls ls -F',
619 620 # long ls
620 621 'll ls -lF',
621 622 # color ls
622 623 'lc ls -F -o --color',
623 624 # ls normal files only
624 625 'lf ls -F -o --color %l | grep ^-',
625 626 # ls symbolic links
626 627 'lk ls -F -o --color %l | grep ^l',
627 628 # directories or links to directories,
628 629 'ldir ls -F -o --color %l | grep /$',
629 630 # things which are executable
630 631 'lx ls -F -o --color %l | grep ^-..x',
631 632 )
632 633 elif os.name in ['nt','dos']:
633 634 auto_alias = ('dir dir /on', 'ls dir /on',
634 635 'ddir dir /ad /on', 'ldir dir /ad /on',
635 636 'mkdir mkdir','rmdir rmdir','echo echo',
636 637 'ren ren','cls cls','copy copy')
637 638 else:
638 639 auto_alias = ()
639 640 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
640 641 # Call the actual (public) initializer
641 642 self.init_auto_alias()
642 643 # end __init__
643 644
644 645 def post_config_initialization(self):
645 646 """Post configuration init method
646 647
647 648 This is called after the configuration files have been processed to
648 649 'finalize' the initialization."""
649 650
650 651 rc = self.rc
651 652
652 653 # Load readline proper
653 654 if rc.readline:
654 655 self.init_readline()
655 656
656 657 # log system
657 658 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
658 659 # local shortcut, this is used a LOT
659 660 self.log = self.logger.log
660 661
661 662 # Initialize cache, set in/out prompts and printing system
662 663 self.outputcache = CachedOutput(self,
663 664 rc.cache_size,
664 665 rc.pprint,
665 666 input_sep = rc.separate_in,
666 667 output_sep = rc.separate_out,
667 668 output_sep2 = rc.separate_out2,
668 669 ps1 = rc.prompt_in1,
669 670 ps2 = rc.prompt_in2,
670 671 ps_out = rc.prompt_out,
671 672 pad_left = rc.prompts_pad_left)
672 673
673 674 # user may have over-ridden the default print hook:
674 675 try:
675 676 self.outputcache.__class__.display = self.hooks.display
676 677 except AttributeError:
677 678 pass
678 679
679 680 # I don't like assigning globally to sys, because it means when embedding
680 681 # instances, each embedded instance overrides the previous choice. But
681 682 # sys.displayhook seems to be called internally by exec, so I don't see a
682 683 # way around it.
683 684 sys.displayhook = self.outputcache
684 685
685 686 # Set user colors (don't do it in the constructor above so that it
686 687 # doesn't crash if colors option is invalid)
687 688 self.magic_colors(rc.colors)
688 689
689 690 # Set calling of pdb on exceptions
690 691 self.call_pdb = rc.pdb
691 692
692 693 # Load user aliases
693 694 for alias in rc.alias:
694 695 self.magic_alias(alias)
695 696
696 697 # dynamic data that survives through sessions
697 698 # XXX make the filename a config option?
698 699 persist_base = 'persist'
699 700 if rc.profile:
700 701 persist_base += '_%s' % rc.profile
701 702 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
702 703
703 704 try:
704 705 self.persist = pickle.load(file(self.persist_fname))
705 706 except:
706 707 self.persist = {}
707 708
708 709
709 710 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
710 711 try:
711 712 obj = pickle.loads(value)
712 713 except:
713 714
714 715 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
715 716 print "The error was:",sys.exc_info()[0]
716 717 continue
717 718
718 719
719 720 self.user_ns[key] = obj
720
721
722
723
721
724 722 def set_hook(self,name,hook):
725 723 """set_hook(name,hook) -> sets an internal IPython hook.
726 724
727 725 IPython exposes some of its internal API as user-modifiable hooks. By
728 726 resetting one of these hooks, you can modify IPython's behavior to
729 727 call at runtime your own routines."""
730 728
731 729 # At some point in the future, this should validate the hook before it
732 730 # accepts it. Probably at least check that the hook takes the number
733 731 # of args it's supposed to.
734 732 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
735 733
736 734 def set_custom_exc(self,exc_tuple,handler):
737 735 """set_custom_exc(exc_tuple,handler)
738 736
739 737 Set a custom exception handler, which will be called if any of the
740 738 exceptions in exc_tuple occur in the mainloop (specifically, in the
741 739 runcode() method.
742 740
743 741 Inputs:
744 742
745 743 - exc_tuple: a *tuple* of valid exceptions to call the defined
746 744 handler for. It is very important that you use a tuple, and NOT A
747 745 LIST here, because of the way Python's except statement works. If
748 746 you only want to trap a single exception, use a singleton tuple:
749 747
750 748 exc_tuple == (MyCustomException,)
751 749
752 750 - handler: this must be defined as a function with the following
753 751 basic interface: def my_handler(self,etype,value,tb).
754 752
755 753 This will be made into an instance method (via new.instancemethod)
756 754 of IPython itself, and it will be called if any of the exceptions
757 755 listed in the exc_tuple are caught. If the handler is None, an
758 756 internal basic one is used, which just prints basic info.
759 757
760 758 WARNING: by putting in your own exception handler into IPython's main
761 759 execution loop, you run a very good chance of nasty crashes. This
762 760 facility should only be used if you really know what you are doing."""
763 761
764 762 assert type(exc_tuple)==type(()) , \
765 763 "The custom exceptions must be given AS A TUPLE."
766 764
767 765 def dummy_handler(self,etype,value,tb):
768 766 print '*** Simple custom exception handler ***'
769 767 print 'Exception type :',etype
770 768 print 'Exception value:',value
771 769 print 'Traceback :',tb
772 770 print 'Source code :','\n'.join(self.buffer)
773 771
774 772 if handler is None: handler = dummy_handler
775 773
776 774 self.CustomTB = new.instancemethod(handler,self,self.__class__)
777 775 self.custom_exceptions = exc_tuple
778 776
779 777 def set_custom_completer(self,completer,pos=0):
780 778 """set_custom_completer(completer,pos=0)
781 779
782 780 Adds a new custom completer function.
783 781
784 782 The position argument (defaults to 0) is the index in the completers
785 783 list where you want the completer to be inserted."""
786 784
787 785 newcomp = new.instancemethod(completer,self.Completer,
788 786 self.Completer.__class__)
789 787 self.Completer.matchers.insert(pos,newcomp)
790 788
791 789 def _get_call_pdb(self):
792 790 return self._call_pdb
793 791
794 792 def _set_call_pdb(self,val):
795 793
796 794 if val not in (0,1,False,True):
797 795 raise ValueError,'new call_pdb value must be boolean'
798 796
799 797 # store value in instance
800 798 self._call_pdb = val
801 799
802 800 # notify the actual exception handlers
803 801 self.InteractiveTB.call_pdb = val
804 802 if self.isthreaded:
805 803 try:
806 804 self.sys_excepthook.call_pdb = val
807 805 except:
808 806 warn('Failed to activate pdb for threaded exception handler')
809 807
810 808 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
811 809 'Control auto-activation of pdb at exceptions')
812 810
813 811 def complete(self,text):
814 812 """Return a sorted list of all possible completions on text.
815 813
816 814 Inputs:
817 815
818 816 - text: a string of text to be completed on.
819 817
820 818 This is a wrapper around the completion mechanism, similar to what
821 819 readline does at the command line when the TAB key is hit. By
822 820 exposing it as a method, it can be used by other non-readline
823 821 environments (such as GUIs) for text completion.
824 822
825 823 Simple usage example:
826 824
827 825 In [1]: x = 'hello'
828 826
829 827 In [2]: __IP.complete('x.l')
830 828 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
831 829
832 830 complete = self.Completer.complete
833 831 state = 0
834 832 # use a dict so we get unique keys, since ipyhton's multiple
835 833 # completers can return duplicates.
836 834 comps = {}
837 835 while True:
838 836 newcomp = complete(text,state)
839 837 if newcomp is None:
840 838 break
841 839 comps[newcomp] = 1
842 840 state += 1
843 841 outcomps = comps.keys()
844 842 outcomps.sort()
845 843 return outcomps
846 844
847 845 def set_completer_frame(self, frame):
848 846 if frame:
849 847 self.Completer.namespace = frame.f_locals
850 848 self.Completer.global_namespace = frame.f_globals
851 849 else:
852 850 self.Completer.namespace = self.user_ns
853 851 self.Completer.global_namespace = self.user_global_ns
854 852
855 853 def init_auto_alias(self):
856 854 """Define some aliases automatically.
857 855
858 856 These are ALL parameter-less aliases"""
859 857 for alias,cmd in self.auto_alias:
860 858 self.alias_table[alias] = (0,cmd)
861 859
862 860 def alias_table_validate(self,verbose=0):
863 861 """Update information about the alias table.
864 862
865 863 In particular, make sure no Python keywords/builtins are in it."""
866 864
867 865 no_alias = self.no_alias
868 866 for k in self.alias_table.keys():
869 867 if k in no_alias:
870 868 del self.alias_table[k]
871 869 if verbose:
872 870 print ("Deleting alias <%s>, it's a Python "
873 871 "keyword or builtin." % k)
874 872
875 873 def set_autoindent(self,value=None):
876 874 """Set the autoindent flag, checking for readline support.
877 875
878 876 If called with no arguments, it acts as a toggle."""
879 877
880 878 if not self.has_readline:
881 879 if os.name == 'posix':
882 880 warn("The auto-indent feature requires the readline library")
883 881 self.autoindent = 0
884 882 return
885 883 if value is None:
886 884 self.autoindent = not self.autoindent
887 885 else:
888 886 self.autoindent = value
889 887
890 888 def rc_set_toggle(self,rc_field,value=None):
891 889 """Set or toggle a field in IPython's rc config. structure.
892 890
893 891 If called with no arguments, it acts as a toggle.
894 892
895 893 If called with a non-existent field, the resulting AttributeError
896 894 exception will propagate out."""
897 895
898 896 rc_val = getattr(self.rc,rc_field)
899 897 if value is None:
900 898 value = not rc_val
901 899 setattr(self.rc,rc_field,value)
902 900
903 901 def user_setup(self,ipythondir,rc_suffix,mode='install'):
904 902 """Install the user configuration directory.
905 903
906 904 Can be called when running for the first time or to upgrade the user's
907 905 .ipython/ directory with the mode parameter. Valid modes are 'install'
908 906 and 'upgrade'."""
909 907
910 908 def wait():
911 909 try:
912 910 raw_input("Please press <RETURN> to start IPython.")
913 911 except EOFError:
914 912 print >> Term.cout
915 913 print '*'*70
916 914
917 915 cwd = os.getcwd() # remember where we started
918 916 glb = glob.glob
919 917 print '*'*70
920 918 if mode == 'install':
921 919 print \
922 920 """Welcome to IPython. I will try to create a personal configuration directory
923 921 where you can customize many aspects of IPython's functionality in:\n"""
924 922 else:
925 923 print 'I am going to upgrade your configuration in:'
926 924
927 925 print ipythondir
928 926
929 927 rcdirend = os.path.join('IPython','UserConfig')
930 928 cfg = lambda d: os.path.join(d,rcdirend)
931 929 try:
932 930 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
933 931 except IOError:
934 932 warning = """
935 933 Installation error. IPython's directory was not found.
936 934
937 935 Check the following:
938 936
939 937 The ipython/IPython directory should be in a directory belonging to your
940 938 PYTHONPATH environment variable (that is, it should be in a directory
941 939 belonging to sys.path). You can copy it explicitly there or just link to it.
942 940
943 941 IPython will proceed with builtin defaults.
944 942 """
945 943 warn(warning)
946 944 wait()
947 945 return
948 946
949 947 if mode == 'install':
950 948 try:
951 949 shutil.copytree(rcdir,ipythondir)
952 950 os.chdir(ipythondir)
953 951 rc_files = glb("ipythonrc*")
954 952 for rc_file in rc_files:
955 953 os.rename(rc_file,rc_file+rc_suffix)
956 954 except:
957 955 warning = """
958 956
959 957 There was a problem with the installation:
960 958 %s
961 959 Try to correct it or contact the developers if you think it's a bug.
962 960 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
963 961 warn(warning)
964 962 wait()
965 963 return
966 964
967 965 elif mode == 'upgrade':
968 966 try:
969 967 os.chdir(ipythondir)
970 968 except:
971 969 print """
972 970 Can not upgrade: changing to directory %s failed. Details:
973 971 %s
974 972 """ % (ipythondir,sys.exc_info()[1])
975 973 wait()
976 974 return
977 975 else:
978 976 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
979 977 for new_full_path in sources:
980 978 new_filename = os.path.basename(new_full_path)
981 979 if new_filename.startswith('ipythonrc'):
982 980 new_filename = new_filename + rc_suffix
983 981 # The config directory should only contain files, skip any
984 982 # directories which may be there (like CVS)
985 983 if os.path.isdir(new_full_path):
986 984 continue
987 985 if os.path.exists(new_filename):
988 986 old_file = new_filename+'.old'
989 987 if os.path.exists(old_file):
990 988 os.remove(old_file)
991 989 os.rename(new_filename,old_file)
992 990 shutil.copy(new_full_path,new_filename)
993 991 else:
994 992 raise ValueError,'unrecognized mode for install:',`mode`
995 993
996 994 # Fix line-endings to those native to each platform in the config
997 995 # directory.
998 996 try:
999 997 os.chdir(ipythondir)
1000 998 except:
1001 999 print """
1002 1000 Problem: changing to directory %s failed.
1003 1001 Details:
1004 1002 %s
1005 1003
1006 1004 Some configuration files may have incorrect line endings. This should not
1007 1005 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1008 1006 wait()
1009 1007 else:
1010 1008 for fname in glb('ipythonrc*'):
1011 1009 try:
1012 1010 native_line_ends(fname,backup=0)
1013 1011 except IOError:
1014 1012 pass
1015 1013
1016 1014 if mode == 'install':
1017 1015 print """
1018 1016 Successful installation!
1019 1017
1020 1018 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1021 1019 IPython manual (there are both HTML and PDF versions supplied with the
1022 1020 distribution) to make sure that your system environment is properly configured
1023 1021 to take advantage of IPython's features."""
1024 1022 else:
1025 1023 print """
1026 1024 Successful upgrade!
1027 1025
1028 1026 All files in your directory:
1029 1027 %(ipythondir)s
1030 1028 which would have been overwritten by the upgrade were backed up with a .old
1031 1029 extension. If you had made particular customizations in those files you may
1032 1030 want to merge them back into the new files.""" % locals()
1033 1031 wait()
1034 1032 os.chdir(cwd)
1035 1033 # end user_setup()
1036 1034
1037 1035 def atexit_operations(self):
1038 1036 """This will be executed at the time of exit.
1039 1037
1040 1038 Saving of persistent data should be performed here. """
1041 1039
1042 1040 # input history
1043 1041 self.savehist()
1044 1042
1045 1043 # Cleanup all tempfiles left around
1046 1044 for tfile in self.tempfiles:
1047 1045 try:
1048 1046 os.unlink(tfile)
1049 1047 except OSError:
1050 1048 pass
1051 1049
1052 1050 # save the "persistent data" catch-all dictionary
1053 1051 try:
1054 1052 pickle.dump(self.persist, open(self.persist_fname,"w"))
1055 1053 except:
1056 1054 print "*** ERROR *** persistent data saving failed."
1057 1055
1058 1056 def savehist(self):
1059 1057 """Save input history to a file (via readline library)."""
1060 1058 try:
1061 1059 self.readline.write_history_file(self.histfile)
1062 1060 except:
1063 1061 print 'Unable to save IPython command history to file: ' + \
1064 1062 `self.histfile`
1065 1063
1066 1064 def pre_readline(self):
1067 1065 """readline hook to be used at the start of each line.
1068 1066
1069 1067 Currently it handles auto-indent only."""
1070 1068
1071 1069 self.readline.insert_text(self.indent_current)
1072 1070
1073 1071 def init_readline(self):
1074 1072 """Command history completion/saving/reloading."""
1075 1073 try:
1076 1074 import readline
1077 1075 except ImportError:
1078 1076 self.has_readline = 0
1079 1077 self.readline = None
1080 1078 # no point in bugging windows users with this every time:
1081 1079 if os.name == 'posix':
1082 1080 warn('Readline services not available on this platform.')
1083 1081 else:
1084 1082 import atexit
1085 1083 from IPython.completer import IPCompleter
1086 1084 self.Completer = IPCompleter(self,
1087 1085 self.user_ns,
1088 1086 self.user_global_ns,
1089 1087 self.rc.readline_omit__names,
1090 1088 self.alias_table)
1091 1089
1092 1090 # Platform-specific configuration
1093 1091 if os.name == 'nt':
1094 1092 self.readline_startup_hook = readline.set_pre_input_hook
1095 1093 else:
1096 1094 self.readline_startup_hook = readline.set_startup_hook
1097 1095
1098 1096 # Load user's initrc file (readline config)
1099 1097 inputrc_name = os.environ.get('INPUTRC')
1100 1098 if inputrc_name is None:
1101 1099 home_dir = get_home_dir()
1102 1100 if home_dir is not None:
1103 1101 inputrc_name = os.path.join(home_dir,'.inputrc')
1104 1102 if os.path.isfile(inputrc_name):
1105 1103 try:
1106 1104 readline.read_init_file(inputrc_name)
1107 1105 except:
1108 1106 warn('Problems reading readline initialization file <%s>'
1109 1107 % inputrc_name)
1110 1108
1111 1109 self.has_readline = 1
1112 1110 self.readline = readline
1113 1111 # save this in sys so embedded copies can restore it properly
1114 1112 sys.ipcompleter = self.Completer.complete
1115 1113 readline.set_completer(self.Completer.complete)
1116 1114
1117 1115 # Configure readline according to user's prefs
1118 1116 for rlcommand in self.rc.readline_parse_and_bind:
1119 1117 readline.parse_and_bind(rlcommand)
1120 1118
1121 1119 # remove some chars from the delimiters list
1122 1120 delims = readline.get_completer_delims()
1123 1121 delims = delims.translate(string._idmap,
1124 1122 self.rc.readline_remove_delims)
1125 1123 readline.set_completer_delims(delims)
1126 1124 # otherwise we end up with a monster history after a while:
1127 1125 readline.set_history_length(1000)
1128 1126 try:
1129 1127 #print '*** Reading readline history' # dbg
1130 1128 readline.read_history_file(self.histfile)
1131 1129 except IOError:
1132 1130 pass # It doesn't exist yet.
1133 1131
1134 1132 atexit.register(self.atexit_operations)
1135 1133 del atexit
1136 1134
1137 1135 # Configure auto-indent for all platforms
1138 1136 self.set_autoindent(self.rc.autoindent)
1139 1137
1140 1138 def _should_recompile(self,e):
1141 1139 """Utility routine for edit_syntax_error"""
1142 1140
1143 1141 if e.filename in ('<ipython console>','<input>','<string>',
1144 1142 '<console>'):
1145 1143 return False
1146 1144 try:
1147 1145 if not ask_yes_no('Return to editor to correct syntax error? '
1148 1146 '[Y/n] ','y'):
1149 1147 return False
1150 1148 except EOFError:
1151 1149 return False
1152 1150 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1153 1151 return True
1154 1152
1155 1153 def edit_syntax_error(self):
1156 1154 """The bottom half of the syntax error handler called in the main loop.
1157 1155
1158 1156 Loop until syntax error is fixed or user cancels.
1159 1157 """
1160 1158
1161 1159 while self.SyntaxTB.last_syntax_error:
1162 1160 # copy and clear last_syntax_error
1163 1161 err = self.SyntaxTB.clear_err_state()
1164 1162 if not self._should_recompile(err):
1165 1163 return
1166 1164 try:
1167 1165 # may set last_syntax_error again if a SyntaxError is raised
1168 1166 self.safe_execfile(err.filename,self.shell.user_ns)
1169 1167 except:
1170 1168 self.showtraceback()
1171 1169 else:
1172 1170 f = file(err.filename)
1173 1171 try:
1174 1172 sys.displayhook(f.read())
1175 1173 finally:
1176 1174 f.close()
1177 1175
1178 1176 def showsyntaxerror(self, filename=None):
1179 1177 """Display the syntax error that just occurred.
1180 1178
1181 1179 This doesn't display a stack trace because there isn't one.
1182 1180
1183 1181 If a filename is given, it is stuffed in the exception instead
1184 1182 of what was there before (because Python's parser always uses
1185 1183 "<string>" when reading from a string).
1186 1184 """
1187 1185 etype, value, last_traceback = sys.exc_info()
1188 1186 if filename and etype is SyntaxError:
1189 1187 # Work hard to stuff the correct filename in the exception
1190 1188 try:
1191 1189 msg, (dummy_filename, lineno, offset, line) = value
1192 1190 except:
1193 1191 # Not the format we expect; leave it alone
1194 1192 pass
1195 1193 else:
1196 1194 # Stuff in the right filename
1197 1195 try:
1198 1196 # Assume SyntaxError is a class exception
1199 1197 value = SyntaxError(msg, (filename, lineno, offset, line))
1200 1198 except:
1201 1199 # If that failed, assume SyntaxError is a string
1202 1200 value = msg, (filename, lineno, offset, line)
1203 1201 self.SyntaxTB(etype,value,[])
1204 1202
1205 1203 def debugger(self):
1206 1204 """Call the pdb debugger."""
1207 1205
1208 1206 if not self.rc.pdb:
1209 1207 return
1210 1208 pdb.pm()
1211 1209
1212 1210 def showtraceback(self,exc_tuple = None,filename=None):
1213 1211 """Display the exception that just occurred."""
1214 1212
1215 1213 # Though this won't be called by syntax errors in the input line,
1216 1214 # there may be SyntaxError cases whith imported code.
1217 1215 if exc_tuple is None:
1218 1216 type, value, tb = sys.exc_info()
1219 1217 else:
1220 1218 type, value, tb = exc_tuple
1221 1219 if type is SyntaxError:
1222 1220 self.showsyntaxerror(filename)
1223 1221 else:
1224 1222 self.InteractiveTB()
1225 1223 if self.InteractiveTB.call_pdb and self.has_readline:
1226 1224 # pdb mucks up readline, fix it back
1227 1225 self.readline.set_completer(self.Completer.complete)
1228 1226
1229 1227 def mainloop(self,banner=None):
1230 1228 """Creates the local namespace and starts the mainloop.
1231 1229
1232 1230 If an optional banner argument is given, it will override the
1233 1231 internally created default banner."""
1234 1232
1235 1233 if self.rc.c: # Emulate Python's -c option
1236 1234 self.exec_init_cmd()
1237 1235 if banner is None:
1238 1236 if self.rc.banner:
1239 1237 banner = self.BANNER+self.banner2
1240 1238 else:
1241 1239 banner = ''
1242 1240 self.interact(banner)
1243 1241
1244 1242 def exec_init_cmd(self):
1245 1243 """Execute a command given at the command line.
1246 1244
1247 1245 This emulates Python's -c option."""
1248 1246
1249 1247 sys.argv = ['-c']
1250 1248 self.push(self.rc.c)
1251 1249
1252 1250 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1253 1251 """Embeds IPython into a running python program.
1254 1252
1255 1253 Input:
1256 1254
1257 1255 - header: An optional header message can be specified.
1258 1256
1259 1257 - local_ns, global_ns: working namespaces. If given as None, the
1260 1258 IPython-initialized one is updated with __main__.__dict__, so that
1261 1259 program variables become visible but user-specific configuration
1262 1260 remains possible.
1263 1261
1264 1262 - stack_depth: specifies how many levels in the stack to go to
1265 1263 looking for namespaces (when local_ns and global_ns are None). This
1266 1264 allows an intermediate caller to make sure that this function gets
1267 1265 the namespace from the intended level in the stack. By default (0)
1268 1266 it will get its locals and globals from the immediate caller.
1269 1267
1270 1268 Warning: it's possible to use this in a program which is being run by
1271 1269 IPython itself (via %run), but some funny things will happen (a few
1272 1270 globals get overwritten). In the future this will be cleaned up, as
1273 1271 there is no fundamental reason why it can't work perfectly."""
1274 1272
1275 1273 # Get locals and globals from caller
1276 1274 if local_ns is None or global_ns is None:
1277 1275 call_frame = sys._getframe(stack_depth).f_back
1278 1276
1279 1277 if local_ns is None:
1280 1278 local_ns = call_frame.f_locals
1281 1279 if global_ns is None:
1282 1280 global_ns = call_frame.f_globals
1283 1281
1284 1282 # Update namespaces and fire up interpreter
1285 1283 self.user_ns = local_ns
1286 1284 self.user_global_ns = global_ns
1287 1285
1288 1286 # Patch for global embedding to make sure that things don't overwrite
1289 1287 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1290 1288 # FIXME. Test this a bit more carefully (the if.. is new)
1291 1289 if local_ns is None and global_ns is None:
1292 1290 self.user_global_ns.update(__main__.__dict__)
1293 1291
1294 1292 # make sure the tab-completer has the correct frame information, so it
1295 1293 # actually completes using the frame's locals/globals
1296 1294 self.set_completer_frame(call_frame)
1297 1295
1298 1296 self.interact(header)
1299 1297
1300 1298 def interact(self, banner=None):
1301 1299 """Closely emulate the interactive Python console.
1302 1300
1303 1301 The optional banner argument specify the banner to print
1304 1302 before the first interaction; by default it prints a banner
1305 1303 similar to the one printed by the real Python interpreter,
1306 1304 followed by the current class name in parentheses (so as not
1307 1305 to confuse this with the real interpreter -- since it's so
1308 1306 close!).
1309 1307
1310 1308 """
1311 1309 cprt = 'Type "copyright", "credits" or "license" for more information.'
1312 1310 if banner is None:
1313 1311 self.write("Python %s on %s\n%s\n(%s)\n" %
1314 1312 (sys.version, sys.platform, cprt,
1315 1313 self.__class__.__name__))
1316 1314 else:
1317 1315 self.write(banner)
1318 1316
1319 1317 more = 0
1320 1318
1321 1319 # Mark activity in the builtins
1322 1320 __builtin__.__dict__['__IPYTHON__active'] += 1
1323 1321
1324 1322 # exit_now is set by a call to %Exit or %Quit
1325 1323 while not self.exit_now:
1326 1324 try:
1327 1325 if more:
1328 1326 prompt = self.outputcache.prompt2
1329 1327 if self.autoindent:
1330 1328 self.readline_startup_hook(self.pre_readline)
1331 1329 else:
1332 1330 prompt = self.outputcache.prompt1
1333 1331 try:
1334 1332 line = self.raw_input(prompt,more)
1335 1333 if self.autoindent:
1336 1334 self.readline_startup_hook(None)
1337 1335 except EOFError:
1338 1336 if self.autoindent:
1339 1337 self.readline_startup_hook(None)
1340 1338 self.write("\n")
1341 1339 self.exit()
1342 1340 else:
1343 1341 more = self.push(line)
1344 1342
1345 1343 if (self.SyntaxTB.last_syntax_error and
1346 1344 self.rc.autoedit_syntax):
1347 1345 self.edit_syntax_error()
1348 1346
1349 1347 except KeyboardInterrupt:
1350 1348 self.write("\nKeyboardInterrupt\n")
1351 1349 self.resetbuffer()
1352 1350 more = 0
1353 1351 # keep cache in sync with the prompt counter:
1354 1352 self.outputcache.prompt_count -= 1
1355 1353
1356 1354 if self.autoindent:
1357 1355 self.indent_current_nsp = 0
1358 1356 self.indent_current = ' '* self.indent_current_nsp
1359 1357
1360 1358 except bdb.BdbQuit:
1361 1359 warn("The Python debugger has exited with a BdbQuit exception.\n"
1362 1360 "Because of how pdb handles the stack, it is impossible\n"
1363 1361 "for IPython to properly format this particular exception.\n"
1364 1362 "IPython will resume normal operation.")
1365 1363
1366 1364 # We are off again...
1367 1365 __builtin__.__dict__['__IPYTHON__active'] -= 1
1368 1366
1369 1367 def excepthook(self, type, value, tb):
1370 1368 """One more defense for GUI apps that call sys.excepthook.
1371 1369
1372 1370 GUI frameworks like wxPython trap exceptions and call
1373 1371 sys.excepthook themselves. I guess this is a feature that
1374 1372 enables them to keep running after exceptions that would
1375 1373 otherwise kill their mainloop. This is a bother for IPython
1376 1374 which excepts to catch all of the program exceptions with a try:
1377 1375 except: statement.
1378 1376
1379 1377 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1380 1378 any app directly invokes sys.excepthook, it will look to the user like
1381 1379 IPython crashed. In order to work around this, we can disable the
1382 1380 CrashHandler and replace it with this excepthook instead, which prints a
1383 1381 regular traceback using our InteractiveTB. In this fashion, apps which
1384 1382 call sys.excepthook will generate a regular-looking exception from
1385 1383 IPython, and the CrashHandler will only be triggered by real IPython
1386 1384 crashes.
1387 1385
1388 1386 This hook should be used sparingly, only in places which are not likely
1389 1387 to be true IPython errors.
1390 1388 """
1391 1389
1392 1390 self.InteractiveTB(type, value, tb, tb_offset=0)
1393 1391 if self.InteractiveTB.call_pdb and self.has_readline:
1394 1392 self.readline.set_completer(self.Completer.complete)
1395 1393
1396 1394 def call_alias(self,alias,rest=''):
1397 1395 """Call an alias given its name and the rest of the line.
1398 1396
1399 1397 This function MUST be given a proper alias, because it doesn't make
1400 1398 any checks when looking up into the alias table. The caller is
1401 1399 responsible for invoking it only with a valid alias."""
1402 1400
1403 1401 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1404 1402 nargs,cmd = self.alias_table[alias]
1405 1403 # Expand the %l special to be the user's input line
1406 1404 if cmd.find('%l') >= 0:
1407 1405 cmd = cmd.replace('%l',rest)
1408 1406 rest = ''
1409 1407 if nargs==0:
1410 1408 # Simple, argument-less aliases
1411 1409 cmd = '%s %s' % (cmd,rest)
1412 1410 else:
1413 1411 # Handle aliases with positional arguments
1414 1412 args = rest.split(None,nargs)
1415 1413 if len(args)< nargs:
1416 1414 error('Alias <%s> requires %s arguments, %s given.' %
1417 1415 (alias,nargs,len(args)))
1418 1416 return
1419 1417 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1420 1418 # Now call the macro, evaluating in the user's namespace
1421 1419 try:
1422 1420 self.system(cmd)
1423 1421 except:
1424 1422 self.showtraceback()
1425 1423
1426 1424 def autoindent_update(self,line):
1427 1425 """Keep track of the indent level."""
1428 1426 if self.autoindent:
1429 1427 if line:
1430 1428 ini_spaces = ini_spaces_re.match(line)
1431 1429 if ini_spaces:
1432 1430 nspaces = ini_spaces.end()
1433 1431 else:
1434 1432 nspaces = 0
1435 1433 self.indent_current_nsp = nspaces
1436 1434
1437 1435 if line[-1] == ':':
1438 1436 self.indent_current_nsp += 4
1439 1437 elif dedent_re.match(line):
1440 1438 self.indent_current_nsp -= 4
1441 1439 else:
1442 1440 self.indent_current_nsp = 0
1443 1441
1444 1442 # indent_current is the actual string to be inserted
1445 1443 # by the readline hooks for indentation
1446 1444 self.indent_current = ' '* self.indent_current_nsp
1447 1445
1448 1446 def runlines(self,lines):
1449 1447 """Run a string of one or more lines of source.
1450 1448
1451 1449 This method is capable of running a string containing multiple source
1452 1450 lines, as if they had been entered at the IPython prompt. Since it
1453 1451 exposes IPython's processing machinery, the given strings can contain
1454 1452 magic calls (%magic), special shell access (!cmd), etc."""
1455 1453
1456 1454 # We must start with a clean buffer, in case this is run from an
1457 1455 # interactive IPython session (via a magic, for example).
1458 1456 self.resetbuffer()
1459 1457 lines = lines.split('\n')
1460 1458 more = 0
1461 1459 for line in lines:
1462 1460 # skip blank lines so we don't mess up the prompt counter, but do
1463 1461 # NOT skip even a blank line if we are in a code block (more is
1464 1462 # true)
1465 1463 if line or more:
1466 1464 more = self.push(self.prefilter(line,more))
1467 1465 # IPython's runsource returns None if there was an error
1468 1466 # compiling the code. This allows us to stop processing right
1469 1467 # away, so the user gets the error message at the right place.
1470 1468 if more is None:
1471 1469 break
1472 1470 # final newline in case the input didn't have it, so that the code
1473 1471 # actually does get executed
1474 1472 if more:
1475 1473 self.push('\n')
1476 1474
1477 1475 def runsource(self, source, filename='<input>', symbol='single'):
1478 1476 """Compile and run some source in the interpreter.
1479 1477
1480 1478 Arguments are as for compile_command().
1481 1479
1482 1480 One several things can happen:
1483 1481
1484 1482 1) The input is incorrect; compile_command() raised an
1485 1483 exception (SyntaxError or OverflowError). A syntax traceback
1486 1484 will be printed by calling the showsyntaxerror() method.
1487 1485
1488 1486 2) The input is incomplete, and more input is required;
1489 1487 compile_command() returned None. Nothing happens.
1490 1488
1491 1489 3) The input is complete; compile_command() returned a code
1492 1490 object. The code is executed by calling self.runcode() (which
1493 1491 also handles run-time exceptions, except for SystemExit).
1494 1492
1495 1493 The return value is:
1496 1494
1497 1495 - True in case 2
1498 1496
1499 1497 - False in the other cases, unless an exception is raised, where
1500 1498 None is returned instead. This can be used by external callers to
1501 1499 know whether to continue feeding input or not.
1502 1500
1503 1501 The return value can be used to decide whether to use sys.ps1 or
1504 1502 sys.ps2 to prompt the next line."""
1505 1503
1506 1504 try:
1507 1505 code = self.compile(source,filename,symbol)
1508 1506 except (OverflowError, SyntaxError, ValueError):
1509 1507 # Case 1
1510 1508 self.showsyntaxerror(filename)
1511 1509 return None
1512 1510
1513 1511 if code is None:
1514 1512 # Case 2
1515 1513 return True
1516 1514
1517 1515 # Case 3
1518 1516 # We store the code object so that threaded shells and
1519 1517 # custom exception handlers can access all this info if needed.
1520 1518 # The source corresponding to this can be obtained from the
1521 1519 # buffer attribute as '\n'.join(self.buffer).
1522 1520 self.code_to_run = code
1523 1521 # now actually execute the code object
1524 1522 if self.runcode(code) == 0:
1525 1523 return False
1526 1524 else:
1527 1525 return None
1528 1526
1529 1527 def runcode(self,code_obj):
1530 1528 """Execute a code object.
1531 1529
1532 1530 When an exception occurs, self.showtraceback() is called to display a
1533 1531 traceback.
1534 1532
1535 1533 Return value: a flag indicating whether the code to be run completed
1536 1534 successfully:
1537 1535
1538 1536 - 0: successful execution.
1539 1537 - 1: an error occurred.
1540 1538 """
1541 1539
1542 1540 # Set our own excepthook in case the user code tries to call it
1543 1541 # directly, so that the IPython crash handler doesn't get triggered
1544 1542 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545 1543
1546 1544 # we save the original sys.excepthook in the instance, in case config
1547 1545 # code (such as magics) needs access to it.
1548 1546 self.sys_excepthook = old_excepthook
1549 1547 outflag = 1 # happens in more places, so it's easier as default
1550 1548 try:
1551 1549 try:
1552 1550 # Embedded instances require separate global/local namespaces
1553 1551 # so they can see both the surrounding (local) namespace and
1554 1552 # the module-level globals when called inside another function.
1555 1553 if self.embedded:
1556 1554 exec code_obj in self.user_global_ns, self.user_ns
1557 1555 # Normal (non-embedded) instances should only have a single
1558 1556 # namespace for user code execution, otherwise functions won't
1559 1557 # see interactive top-level globals.
1560 1558 else:
1561 1559 exec code_obj in self.user_ns
1562 1560 finally:
1563 1561 # Reset our crash handler in place
1564 1562 sys.excepthook = old_excepthook
1565 1563 except SystemExit:
1566 1564 self.resetbuffer()
1567 1565 self.showtraceback()
1568 1566 warn("Type exit or quit to exit IPython "
1569 1567 "(%Exit or %Quit do so unconditionally).",level=1)
1570 1568 except self.custom_exceptions:
1571 1569 etype,value,tb = sys.exc_info()
1572 1570 self.CustomTB(etype,value,tb)
1573 1571 except:
1574 1572 self.showtraceback()
1575 1573 else:
1576 1574 outflag = 0
1577 1575 if softspace(sys.stdout, 0):
1578 1576 print
1579 1577 # Flush out code object which has been run (and source)
1580 1578 self.code_to_run = None
1581 1579 return outflag
1582 1580
1583 1581 def push(self, line):
1584 1582 """Push a line to the interpreter.
1585 1583
1586 1584 The line should not have a trailing newline; it may have
1587 1585 internal newlines. The line is appended to a buffer and the
1588 1586 interpreter's runsource() method is called with the
1589 1587 concatenated contents of the buffer as source. If this
1590 1588 indicates that the command was executed or invalid, the buffer
1591 1589 is reset; otherwise, the command is incomplete, and the buffer
1592 1590 is left as it was after the line was appended. The return
1593 1591 value is 1 if more input is required, 0 if the line was dealt
1594 1592 with in some way (this is the same as runsource()).
1595 1593 """
1596 1594
1597 1595 # autoindent management should be done here, and not in the
1598 1596 # interactive loop, since that one is only seen by keyboard input. We
1599 1597 # need this done correctly even for code run via runlines (which uses
1600 1598 # push).
1601 1599
1602 1600 #print 'push line: <%s>' % line # dbg
1603 1601 self.autoindent_update(line)
1604 1602
1605 1603 self.buffer.append(line)
1606 1604 more = self.runsource('\n'.join(self.buffer), self.filename)
1607 1605 if not more:
1608 1606 self.resetbuffer()
1609 1607 return more
1610 1608
1611 1609 def resetbuffer(self):
1612 1610 """Reset the input buffer."""
1613 1611 self.buffer[:] = []
1614 1612
1615 1613 def raw_input(self,prompt='',continue_prompt=False):
1616 1614 """Write a prompt and read a line.
1617 1615
1618 1616 The returned line does not include the trailing newline.
1619 1617 When the user enters the EOF key sequence, EOFError is raised.
1620 1618
1621 1619 Optional inputs:
1622 1620
1623 1621 - prompt(''): a string to be printed to prompt the user.
1624 1622
1625 1623 - continue_prompt(False): whether this line is the first one or a
1626 1624 continuation in a sequence of inputs.
1627 1625 """
1628 1626
1629 1627 line = raw_input_original(prompt)
1630 1628 # Try to be reasonably smart about not re-indenting pasted input more
1631 1629 # than necessary. We do this by trimming out the auto-indent initial
1632 1630 # spaces, if the user's actual input started itself with whitespace.
1633 1631 if self.autoindent:
1634 1632 line2 = line[self.indent_current_nsp:]
1635 1633 if line2[0:1] in (' ','\t'):
1636 1634 line = line2
1637 1635 return self.prefilter(line,continue_prompt)
1638 1636
1639 1637 def split_user_input(self,line):
1640 1638 """Split user input into pre-char, function part and rest."""
1641 1639
1642 1640 lsplit = self.line_split.match(line)
1643 1641 if lsplit is None: # no regexp match returns None
1644 1642 try:
1645 1643 iFun,theRest = line.split(None,1)
1646 1644 except ValueError:
1647 1645 iFun,theRest = line,''
1648 1646 pre = re.match('^(\s*)(.*)',line).groups()[0]
1649 1647 else:
1650 1648 pre,iFun,theRest = lsplit.groups()
1651 1649
1652 1650 #print 'line:<%s>' % line # dbg
1653 1651 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1654 1652 return pre,iFun.strip(),theRest
1655 1653
1656 1654 def _prefilter(self, line, continue_prompt):
1657 1655 """Calls different preprocessors, depending on the form of line."""
1658 1656
1659 1657 # All handlers *must* return a value, even if it's blank ('').
1660 1658
1661 1659 # Lines are NOT logged here. Handlers should process the line as
1662 1660 # needed, update the cache AND log it (so that the input cache array
1663 1661 # stays synced).
1664 1662
1665 1663 # This function is _very_ delicate, and since it's also the one which
1666 1664 # determines IPython's response to user input, it must be as efficient
1667 1665 # as possible. For this reason it has _many_ returns in it, trying
1668 1666 # always to exit as quickly as it can figure out what it needs to do.
1669 1667
1670 1668 # This function is the main responsible for maintaining IPython's
1671 1669 # behavior respectful of Python's semantics. So be _very_ careful if
1672 1670 # making changes to anything here.
1673 1671
1674 1672 #.....................................................................
1675 1673 # Code begins
1676 1674
1677 1675 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1678 1676
1679 1677 # save the line away in case we crash, so the post-mortem handler can
1680 1678 # record it
1681 1679 self._last_input_line = line
1682 1680
1683 1681 #print '***line: <%s>' % line # dbg
1684 1682
1685 1683 # the input history needs to track even empty lines
1686 1684 if not line.strip():
1687 1685 if not continue_prompt:
1688 1686 self.outputcache.prompt_count -= 1
1689 1687 return self.handle_normal(line,continue_prompt)
1690 1688 #return self.handle_normal('',continue_prompt)
1691 1689
1692 1690 # print '***cont',continue_prompt # dbg
1693 1691 # special handlers are only allowed for single line statements
1694 1692 if continue_prompt and not self.rc.multi_line_specials:
1695 1693 return self.handle_normal(line,continue_prompt)
1696 1694
1697 1695 # For the rest, we need the structure of the input
1698 1696 pre,iFun,theRest = self.split_user_input(line)
1699 1697 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1700 1698
1701 1699 # First check for explicit escapes in the last/first character
1702 1700 handler = None
1703 1701 if line[-1] == self.ESC_HELP:
1704 1702 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1705 1703 if handler is None:
1706 1704 # look at the first character of iFun, NOT of line, so we skip
1707 1705 # leading whitespace in multiline input
1708 1706 handler = self.esc_handlers.get(iFun[0:1])
1709 1707 if handler is not None:
1710 1708 return handler(line,continue_prompt,pre,iFun,theRest)
1711 1709 # Emacs ipython-mode tags certain input lines
1712 1710 if line.endswith('# PYTHON-MODE'):
1713 1711 return self.handle_emacs(line,continue_prompt)
1714 1712
1715 1713 # Next, check if we can automatically execute this thing
1716 1714
1717 1715 # Allow ! in multi-line statements if multi_line_specials is on:
1718 1716 if continue_prompt and self.rc.multi_line_specials and \
1719 1717 iFun.startswith(self.ESC_SHELL):
1720 1718 return self.handle_shell_escape(line,continue_prompt,
1721 1719 pre=pre,iFun=iFun,
1722 1720 theRest=theRest)
1723 1721
1724 1722 # Let's try to find if the input line is a magic fn
1725 1723 oinfo = None
1726 1724 if hasattr(self,'magic_'+iFun):
1727 1725 # WARNING: _ofind uses getattr(), so it can consume generators and
1728 1726 # cause other side effects.
1729 1727 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1730 1728 if oinfo['ismagic']:
1731 1729 # Be careful not to call magics when a variable assignment is
1732 1730 # being made (ls='hi', for example)
1733 1731 if self.rc.automagic and \
1734 1732 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1735 1733 (self.rc.multi_line_specials or not continue_prompt):
1736 1734 return self.handle_magic(line,continue_prompt,
1737 1735 pre,iFun,theRest)
1738 1736 else:
1739 1737 return self.handle_normal(line,continue_prompt)
1740 1738
1741 1739 # If the rest of the line begins with an (in)equality, assginment or
1742 1740 # function call, we should not call _ofind but simply execute it.
1743 1741 # This avoids spurious geattr() accesses on objects upon assignment.
1744 1742 #
1745 1743 # It also allows users to assign to either alias or magic names true
1746 1744 # python variables (the magic/alias systems always take second seat to
1747 1745 # true python code).
1748 1746 if theRest and theRest[0] in '!=()':
1749 1747 return self.handle_normal(line,continue_prompt)
1750 1748
1751 1749 if oinfo is None:
1752 1750 # let's try to ensure that _oinfo is ONLY called when autocall is
1753 1751 # on. Since it has inevitable potential side effects, at least
1754 1752 # having autocall off should be a guarantee to the user that no
1755 1753 # weird things will happen.
1756 1754
1757 1755 if self.rc.autocall:
1758 1756 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1759 1757 else:
1760 1758 # in this case, all that's left is either an alias or
1761 1759 # processing the line normally.
1762 1760 if iFun in self.alias_table:
1763 1761 return self.handle_alias(line,continue_prompt,
1764 1762 pre,iFun,theRest)
1765 1763 else:
1766 1764 return self.handle_normal(line,continue_prompt)
1767 1765
1768 1766 if not oinfo['found']:
1769 1767 return self.handle_normal(line,continue_prompt)
1770 1768 else:
1771 1769 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1772 1770 if oinfo['isalias']:
1773 1771 return self.handle_alias(line,continue_prompt,
1774 1772 pre,iFun,theRest)
1775 1773
1776 1774 if self.rc.autocall and \
1777 1775 not self.re_exclude_auto.match(theRest) and \
1778 1776 self.re_fun_name.match(iFun) and \
1779 1777 callable(oinfo['obj']) :
1780 1778 #print 'going auto' # dbg
1781 1779 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1782 1780 else:
1783 1781 #print 'was callable?', callable(oinfo['obj']) # dbg
1784 1782 return self.handle_normal(line,continue_prompt)
1785 1783
1786 1784 # If we get here, we have a normal Python line. Log and return.
1787 1785 return self.handle_normal(line,continue_prompt)
1788 1786
1789 1787 def _prefilter_dumb(self, line, continue_prompt):
1790 1788 """simple prefilter function, for debugging"""
1791 1789 return self.handle_normal(line,continue_prompt)
1792 1790
1793 1791 # Set the default prefilter() function (this can be user-overridden)
1794 1792 prefilter = _prefilter
1795 1793
1796 1794 def handle_normal(self,line,continue_prompt=None,
1797 1795 pre=None,iFun=None,theRest=None):
1798 1796 """Handle normal input lines. Use as a template for handlers."""
1799 1797
1800 1798 # With autoindent on, we need some way to exit the input loop, and I
1801 1799 # don't want to force the user to have to backspace all the way to
1802 1800 # clear the line. The rule will be in this case, that either two
1803 1801 # lines of pure whitespace in a row, or a line of pure whitespace but
1804 1802 # of a size different to the indent level, will exit the input loop.
1805 1803
1806 1804 if (continue_prompt and self.autoindent and isspace(line) and
1807 1805 (line != self.indent_current or isspace(self.buffer[-1]))):
1808 1806 line = ''
1809 1807
1810 1808 self.log(line,continue_prompt)
1811 1809 return line
1812 1810
1813 1811 def handle_alias(self,line,continue_prompt=None,
1814 1812 pre=None,iFun=None,theRest=None):
1815 1813 """Handle alias input lines. """
1816 1814
1817 1815 # pre is needed, because it carries the leading whitespace. Otherwise
1818 1816 # aliases won't work in indented sections.
1819 1817 line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest))
1820 1818 self.log(line_out,continue_prompt)
1821 1819 return line_out
1822 1820
1823 1821 def handle_shell_escape(self, line, continue_prompt=None,
1824 1822 pre=None,iFun=None,theRest=None):
1825 1823 """Execute the line in a shell, empty return value"""
1826 1824
1827 1825 #print 'line in :', `line` # dbg
1828 1826 # Example of a special handler. Others follow a similar pattern.
1829 1827 if continue_prompt: # multi-line statements
1830 1828 if iFun.startswith('!!'):
1831 1829 print 'SyntaxError: !! is not allowed in multiline statements'
1832 1830 return pre
1833 1831 else:
1834 1832 cmd = ("%s %s" % (iFun[1:],theRest))
1835 1833 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_")
1836 1834 else: # single-line input
1837 1835 if line.startswith('!!'):
1838 1836 # rewrite iFun/theRest to properly hold the call to %sx and
1839 1837 # the actual command to be executed, so handle_magic can work
1840 1838 # correctly
1841 1839 theRest = '%s %s' % (iFun[2:],theRest)
1842 1840 iFun = 'sx'
1843 1841 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1844 1842 continue_prompt,pre,iFun,theRest)
1845 1843 else:
1846 1844 cmd=line[1:]
1847 1845 line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_")
1848 1846 # update cache/log and return
1849 1847 self.log(line_out,continue_prompt)
1850 1848 return line_out
1851 1849
1852 1850 def handle_magic(self, line, continue_prompt=None,
1853 1851 pre=None,iFun=None,theRest=None):
1854 1852 """Execute magic functions.
1855 1853
1856 1854 Also log them with a prepended # so the log is clean Python."""
1857 1855
1858 1856 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1859 1857 self.log(cmd,continue_prompt)
1860 1858 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1861 1859 return cmd
1862 1860
1863 1861 def handle_auto(self, line, continue_prompt=None,
1864 1862 pre=None,iFun=None,theRest=None):
1865 1863 """Hande lines which can be auto-executed, quoting if requested."""
1866 1864
1867 1865 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1868 1866
1869 1867 # This should only be active for single-line input!
1870 1868 if continue_prompt:
1871 1869 return line
1872 1870
1873 1871 if pre == self.ESC_QUOTE:
1874 1872 # Auto-quote splitting on whitespace
1875 1873 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1876 1874 elif pre == self.ESC_QUOTE2:
1877 1875 # Auto-quote whole string
1878 1876 newcmd = '%s("%s")' % (iFun,theRest)
1879 1877 else:
1880 1878 # Auto-paren
1881 1879 if theRest[0:1] in ('=','['):
1882 1880 # Don't autocall in these cases. They can be either
1883 1881 # rebindings of an existing callable's name, or item access
1884 1882 # for an object which is BOTH callable and implements
1885 1883 # __getitem__.
1886 1884 return '%s %s' % (iFun,theRest)
1887 1885 if theRest.endswith(';'):
1888 1886 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1889 1887 else:
1890 1888 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1891 1889
1892 1890 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1893 1891 # log what is now valid Python, not the actual user input (without the
1894 1892 # final newline)
1895 1893 self.log(newcmd,continue_prompt)
1896 1894 return newcmd
1897 1895
1898 1896 def handle_help(self, line, continue_prompt=None,
1899 1897 pre=None,iFun=None,theRest=None):
1900 1898 """Try to get some help for the object.
1901 1899
1902 1900 obj? or ?obj -> basic information.
1903 1901 obj?? or ??obj -> more details.
1904 1902 """
1905 1903
1906 1904 # We need to make sure that we don't process lines which would be
1907 1905 # otherwise valid python, such as "x=1 # what?"
1908 1906 try:
1909 1907 codeop.compile_command(line)
1910 1908 except SyntaxError:
1911 1909 # We should only handle as help stuff which is NOT valid syntax
1912 1910 if line[0]==self.ESC_HELP:
1913 1911 line = line[1:]
1914 1912 elif line[-1]==self.ESC_HELP:
1915 1913 line = line[:-1]
1916 1914 self.log('#?'+line)
1917 1915 if line:
1918 1916 self.magic_pinfo(line)
1919 1917 else:
1920 1918 page(self.usage,screen_lines=self.rc.screen_length)
1921 1919 return '' # Empty string is needed here!
1922 1920 except:
1923 1921 # Pass any other exceptions through to the normal handler
1924 1922 return self.handle_normal(line,continue_prompt)
1925 1923 else:
1926 1924 # If the code compiles ok, we should handle it normally
1927 1925 return self.handle_normal(line,continue_prompt)
1928 1926
1929 1927 def handle_emacs(self,line,continue_prompt=None,
1930 1928 pre=None,iFun=None,theRest=None):
1931 1929 """Handle input lines marked by python-mode."""
1932 1930
1933 1931 # Currently, nothing is done. Later more functionality can be added
1934 1932 # here if needed.
1935 1933
1936 1934 # The input cache shouldn't be updated
1937 1935
1938 1936 return line
1939 1937
1940 1938 def write(self,data):
1941 1939 """Write a string to the default output"""
1942 1940 Term.cout.write(data)
1943 1941
1944 1942 def write_err(self,data):
1945 1943 """Write a string to the default error output"""
1946 1944 Term.cerr.write(data)
1947 1945
1948 1946 def exit(self):
1949 1947 """Handle interactive exit.
1950 1948
1951 1949 This method sets the exit_now attribute."""
1952 1950
1953 1951 if self.rc.confirm_exit:
1954 1952 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1955 1953 self.exit_now = True
1956 1954 else:
1957 1955 self.exit_now = True
1958 1956 return self.exit_now
1959 1957
1960 1958 def safe_execfile(self,fname,*where,**kw):
1961 1959 fname = os.path.expanduser(fname)
1962 1960
1963 1961 # find things also in current directory
1964 1962 dname = os.path.dirname(fname)
1965 1963 if not sys.path.count(dname):
1966 1964 sys.path.append(dname)
1967 1965
1968 1966 try:
1969 1967 xfile = open(fname)
1970 1968 except:
1971 1969 print >> Term.cerr, \
1972 1970 'Could not open file <%s> for safe execution.' % fname
1973 1971 return None
1974 1972
1975 1973 kw.setdefault('islog',0)
1976 1974 kw.setdefault('quiet',1)
1977 1975 kw.setdefault('exit_ignore',0)
1978 1976 first = xfile.readline()
1979 1977 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1980 1978 xfile.close()
1981 1979 # line by line execution
1982 1980 if first.startswith(loghead) or kw['islog']:
1983 1981 print 'Loading log file <%s> one line at a time...' % fname
1984 1982 if kw['quiet']:
1985 1983 stdout_save = sys.stdout
1986 1984 sys.stdout = StringIO.StringIO()
1987 1985 try:
1988 1986 globs,locs = where[0:2]
1989 1987 except:
1990 1988 try:
1991 1989 globs = locs = where[0]
1992 1990 except:
1993 1991 globs = locs = globals()
1994 1992 badblocks = []
1995 1993
1996 1994 # we also need to identify indented blocks of code when replaying
1997 1995 # logs and put them together before passing them to an exec
1998 1996 # statement. This takes a bit of regexp and look-ahead work in the
1999 1997 # file. It's easiest if we swallow the whole thing in memory
2000 1998 # first, and manually walk through the lines list moving the
2001 1999 # counter ourselves.
2002 2000 indent_re = re.compile('\s+\S')
2003 2001 xfile = open(fname)
2004 2002 filelines = xfile.readlines()
2005 2003 xfile.close()
2006 2004 nlines = len(filelines)
2007 2005 lnum = 0
2008 2006 while lnum < nlines:
2009 2007 line = filelines[lnum]
2010 2008 lnum += 1
2011 2009 # don't re-insert logger status info into cache
2012 2010 if line.startswith('#log#'):
2013 2011 continue
2014 2012 else:
2015 2013 # build a block of code (maybe a single line) for execution
2016 2014 block = line
2017 2015 try:
2018 2016 next = filelines[lnum] # lnum has already incremented
2019 2017 except:
2020 2018 next = None
2021 2019 while next and indent_re.match(next):
2022 2020 block += next
2023 2021 lnum += 1
2024 2022 try:
2025 2023 next = filelines[lnum]
2026 2024 except:
2027 2025 next = None
2028 2026 # now execute the block of one or more lines
2029 2027 try:
2030 2028 exec block in globs,locs
2031 2029 except SystemExit:
2032 2030 pass
2033 2031 except:
2034 2032 badblocks.append(block.rstrip())
2035 2033 if kw['quiet']: # restore stdout
2036 2034 sys.stdout.close()
2037 2035 sys.stdout = stdout_save
2038 2036 print 'Finished replaying log file <%s>' % fname
2039 2037 if badblocks:
2040 2038 print >> sys.stderr, ('\nThe following lines/blocks in file '
2041 2039 '<%s> reported errors:' % fname)
2042 2040
2043 2041 for badline in badblocks:
2044 2042 print >> sys.stderr, badline
2045 2043 else: # regular file execution
2046 2044 try:
2047 2045 execfile(fname,*where)
2048 2046 except SyntaxError:
2049 2047 etype,evalue = sys.exc_info()[:2]
2050 2048 self.SyntaxTB(etype,evalue,[])
2051 2049 warn('Failure executing file: <%s>' % fname)
2052 2050 except SystemExit,status:
2053 2051 if not kw['exit_ignore']:
2054 2052 self.InteractiveTB()
2055 2053 warn('Failure executing file: <%s>' % fname)
2056 2054 except:
2057 2055 self.InteractiveTB()
2058 2056 warn('Failure executing file: <%s>' % fname)
2059 2057
2060 2058 #************************* end of file <iplib.py> *****************************
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now