##// END OF EJS Templates
Merge branch '0.10.2' of https://github.com/TvrtkoM/ipython into TvrtkoM-0.10.2
Fernando Perez -
r3371:cec4ca6d merge
parent child Browse files
Show More
@@ -1,263 +1,264 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Logger class for IPython's logging facilities.
4 4 """
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 # Python standard modules
18 18 import glob
19 19 import os
20 20 import time
21 import sys
21 22
22 23 #****************************************************************************
23 24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 25 # ipython and does input cache management. Finish cleanup later...
25 26
26 27 class Logger(object):
27 28 """A Logfile class with different policies for file creation"""
28 29
29 30 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
30 31
31 32 self._i00,self._i,self._ii,self._iii = '','','',''
32 33
33 34 # this is the full ipython instance, we need some attributes from it
34 35 # which won't exist until later. What a mess, clean up later...
35 36 self.shell = shell
36 37
37 38 self.logfname = logfname
38 39 self.loghead = loghead
39 40 self.logmode = logmode
40 41 self.logfile = None
41 42
42 43 # Whether to log raw or processed input
43 44 self.log_raw_input = False
44 45
45 46 # whether to also log output
46 47 self.log_output = False
47 48
48 49 # whether to put timestamps before each log entry
49 50 self.timestamp = False
50 51
51 52 # activity control flags
52 53 self.log_active = False
53 54
54 55 # logmode is a validated property
55 56 def _set_mode(self,mode):
56 57 if mode not in ['append','backup','global','over','rotate']:
57 58 raise ValueError,'invalid log mode %s given' % mode
58 59 self._logmode = mode
59 60
60 61 def _get_mode(self):
61 62 return self._logmode
62 63
63 64 logmode = property(_get_mode,_set_mode)
64 65
65 66 def logstart(self,logfname=None,loghead=None,logmode=None,
66 67 log_output=False,timestamp=False,log_raw_input=False):
67 68 """Generate a new log-file with a default header.
68 69
69 70 Raises RuntimeError if the log has already been started"""
70 71
71 72 if self.logfile is not None:
72 73 raise RuntimeError('Log file is already active: %s' %
73 74 self.logfname)
74 75
75 76 self.log_active = True
76 77
77 78 # The parameters can override constructor defaults
78 79 if logfname is not None: self.logfname = logfname
79 80 if loghead is not None: self.loghead = loghead
80 81 if logmode is not None: self.logmode = logmode
81 82
82 83 # Parameters not part of the constructor
83 84 self.timestamp = timestamp
84 85 self.log_output = log_output
85 86 self.log_raw_input = log_raw_input
86 87
87 88 # init depending on the log mode requested
88 89 isfile = os.path.isfile
89 90 logmode = self.logmode
90 91
91 92 if logmode == 'append':
92 93 self.logfile = open(self.logfname,'a')
93 94
94 95 elif logmode == 'backup':
95 96 if isfile(self.logfname):
96 97 backup_logname = self.logfname+'~'
97 98 # Manually remove any old backup, since os.rename may fail
98 99 # under Windows.
99 100 if isfile(backup_logname):
100 101 os.remove(backup_logname)
101 102 os.rename(self.logfname,backup_logname)
102 103 self.logfile = open(self.logfname,'w')
103 104
104 105 elif logmode == 'global':
105 106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 107 self.logfile = open(self.logfname, 'a')
107 108
108 109 elif logmode == 'over':
109 110 if isfile(self.logfname):
110 111 os.remove(self.logfname)
111 112 self.logfile = open(self.logfname,'w')
112 113
113 114 elif logmode == 'rotate':
114 115 if isfile(self.logfname):
115 116 if isfile(self.logfname+'.001~'):
116 117 old = glob.glob(self.logfname+'.*~')
117 118 old.sort()
118 119 old.reverse()
119 120 for f in old:
120 121 root, ext = os.path.splitext(f)
121 122 num = int(ext[1:-1])+1
122 123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 124 os.rename(self.logfname, self.logfname+'.001~')
124 125 self.logfile = open(self.logfname,'w')
125 126
126 127 if logmode != 'append':
127 128 self.logfile.write(self.loghead)
128 129
129 130 self.logfile.flush()
130 131
131 132 def switch_log(self,val):
132 133 """Switch logging on/off. val should be ONLY a boolean."""
133 134
134 135 if val not in [False,True,0,1]:
135 136 raise ValueError, \
136 137 'Call switch_log ONLY with a boolean argument, not with:',val
137 138
138 139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139 140
140 141 if self.logfile is None:
141 142 print """
142 143 Logging hasn't been started yet (use logstart for that).
143 144
144 145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 146 which already exists. But you must first start the logging process with
146 147 %logstart (optionally giving a logfile name)."""
147 148
148 149 else:
149 150 if self.log_active == val:
150 151 print 'Logging is already',label[val]
151 152 else:
152 153 print 'Switching logging',label[val]
153 154 self.log_active = not self.log_active
154 155 self.log_active_out = self.log_active
155 156
156 157 def logstate(self):
157 158 """Print a status message about the logger."""
158 159 if self.logfile is None:
159 160 print 'Logging has not been activated.'
160 161 else:
161 162 state = self.log_active and 'active' or 'temporarily suspended'
162 163 print 'Filename :',self.logfname
163 164 print 'Mode :',self.logmode
164 165 print 'Output logging :',self.log_output
165 166 print 'Raw input log :',self.log_raw_input
166 167 print 'Timestamping :',self.timestamp
167 168 print 'State :',state
168 169
169 170 def log(self,line_ori,line_mod,continuation=None):
170 171 """Write the line to a log and create input cache variables _i*.
171 172
172 173 Inputs:
173 174
174 175 - line_ori: unmodified input line from the user. This is not
175 176 necessarily valid Python.
176 177
177 178 - line_mod: possibly modified input, such as the transformations made
178 179 by input prefilters or input handlers of various kinds. This should
179 180 always be valid Python.
180 181
181 182 - continuation: if True, indicates this is part of multi-line input."""
182 183
183 184 # update the auto _i tables
184 185 #print '***logging line',line_mod # dbg
185 186 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
186 187 try:
187 188 input_hist = self.shell.user_ns['_ih']
188 189 except:
189 190 #print 'userns:',self.shell.user_ns.keys() # dbg
190 191 return
191 192
192 193 out_cache = self.shell.outputcache
193 194
194 195 # add blank lines if the input cache fell out of sync.
195 196 if out_cache.do_full_cache and \
196 197 out_cache.prompt_count +1 > len(input_hist):
197 198 input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
198 199
199 200 if not continuation and line_mod:
200 201 self._iii = self._ii
201 202 self._ii = self._i
202 203 self._i = self._i00
203 204 # put back the final \n of every input line
204 205 self._i00 = line_mod+'\n'
205 206 #print 'Logging input:<%s>' % line_mod # dbg
206 207 input_hist.append(self._i00)
207 208 #print '---[%s]' % (len(input_hist)-1,) # dbg
208 209
209 210 # hackish access to top-level namespace to create _i1,_i2... dynamically
210 211 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
211 212 if self.shell.outputcache.do_full_cache:
212 213 in_num = self.shell.outputcache.prompt_count
213 214
214 215 # but if the opposite is true (a macro can produce multiple inputs
215 216 # with no output display called), then bring the output counter in
216 217 # sync:
217 218 last_num = len(input_hist)-1
218 219 if in_num != last_num:
219 220 in_num = self.shell.outputcache.prompt_count = last_num
220 221 new_i = '_i%s' % in_num
221 222 if continuation:
222 223 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
223 224 input_hist[in_num] = self._i00
224 225 to_main[new_i] = self._i00
225 226 self.shell.user_ns.update(to_main)
226 227
227 228 # Write the log line, but decide which one according to the
228 229 # log_raw_input flag, set when the log is started.
229 230 if self.log_raw_input:
230 231 self.log_write(line_ori)
231 232 else:
232 233 self.log_write(line_mod)
233 234
234 235 def log_write(self,data,kind='input'):
235 236 """Write data to the log file, if active"""
236 237
237 238 #print 'data: %r' % data # dbg
238 239 if self.log_active and data:
239 240 write = self.logfile.write
240 241 if kind=='input':
241 242 if self.timestamp:
242 243 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
243 244 time.localtime()))
244 write('%s\n' % data)
245 write('%s\n' % data.encode(sys.stdin.encoding))
245 246 elif kind=='output' and self.log_output:
246 247 odata = '\n'.join(['#[Out]# %s' % s
247 248 for s in data.split('\n')])
248 249 write('%s\n' % odata)
249 250 self.logfile.flush()
250 251
251 252 def logstop(self):
252 253 """Fully stop logging and close log file.
253 254
254 255 In order to start logging again, a new logstart() call needs to be
255 256 made, possibly (though not necessarily) with a new filename, mode and
256 257 other options."""
257 258
258 259 self.logfile.close()
259 260 self.logfile = None
260 261 self.log_active = False
261 262
262 263 # For backwards compatibility, in case anyone was using this.
263 264 close_log = logstop
@@ -1,3540 +1,3540 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #*****************************************************************************
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #*****************************************************************************
12 12
13 13 #****************************************************************************
14 14 # Modules and globals
15 15
16 16 # Python standard modules
17 17 import __builtin__
18 18 import __future__
19 19 import bdb
20 20 import inspect
21 21 import os
22 22 import pdb
23 23 import pydoc
24 24 import sys
25 25 import re
26 26 import tempfile
27 27 import time
28 28 import cPickle as pickle
29 29 import textwrap
30 30 from cStringIO import StringIO
31 31 from getopt import getopt,GetoptError
32 32 from pprint import pprint, pformat
33 33
34 34 # cProfile was added in Python2.5
35 35 try:
36 36 import cProfile as profile
37 37 import pstats
38 38 except ImportError:
39 39 # profile isn't bundled by default in Debian for license reasons
40 40 try:
41 41 import profile,pstats
42 42 except ImportError:
43 43 profile = pstats = None
44 44
45 45 # print_function was added to __future__ in Python2.6, remove this when we drop
46 46 # 2.5 compatibility
47 47 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
48 48 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
49 49
50 50 # Homebrewed
51 51 import IPython
52 52 from IPython import Debugger, OInspect, wildcard
53 53 from IPython.FakeModule import FakeModule
54 54 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 55 from IPython.PyColorize import Parser
56 56 from IPython.ipstruct import Struct
57 57 from IPython.macro import Macro
58 58 from IPython.genutils import *
59 59 from IPython import platutils
60 60 import IPython.generics
61 61 import IPython.ipapi
62 62 from IPython.ipapi import UsageError
63 63 from IPython.testing import decorators as testdec
64 64
65 65 #***************************************************************************
66 66 # Utility functions
67 67 def on_off(tag):
68 68 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 69 return ['OFF','ON'][tag]
70 70
71 71 class Bunch: pass
72 72
73 73 def compress_dhist(dh):
74 74 head, tail = dh[:-10], dh[-10:]
75 75
76 76 newhead = []
77 77 done = set()
78 78 for h in head:
79 79 if h in done:
80 80 continue
81 81 newhead.append(h)
82 82 done.add(h)
83 83
84 84 return newhead + tail
85 85
86 86
87 87 #***************************************************************************
88 88 # Main class implementing Magic functionality
89 89 class Magic:
90 90 """Magic functions for InteractiveShell.
91 91
92 92 Shell functions which can be reached as %function_name. All magic
93 93 functions should accept a string, which they can parse for their own
94 94 needs. This can make some functions easier to type, eg `%cd ../`
95 95 vs. `%cd("../")`
96 96
97 97 ALL definitions MUST begin with the prefix magic_. The user won't need it
98 98 at the command line, but it is is needed in the definition. """
99 99
100 100 # class globals
101 101 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
102 102 'Automagic is ON, % prefix NOT needed for magic functions.']
103 103
104 104 #......................................................................
105 105 # some utility functions
106 106
107 107 def __init__(self,shell):
108 108
109 109 self.options_table = {}
110 110 if profile is None:
111 111 self.magic_prun = self.profile_missing_notice
112 112 self.shell = shell
113 113
114 114 # namespace for holding state we may need
115 115 self._magic_state = Bunch()
116 116
117 117 def profile_missing_notice(self, *args, **kwargs):
118 118 error("""\
119 119 The profile module could not be found. It has been removed from the standard
120 120 python packages because of its non-free license. To use profiling, install the
121 121 python-profiler package from non-free.""")
122 122
123 123 def default_option(self,fn,optstr):
124 124 """Make an entry in the options_table for fn, with value optstr"""
125 125
126 126 if fn not in self.lsmagic():
127 127 error("%s is not a magic function" % fn)
128 128 self.options_table[fn] = optstr
129 129
130 130 def lsmagic(self):
131 131 """Return a list of currently available magic functions.
132 132
133 133 Gives a list of the bare names after mangling (['ls','cd', ...], not
134 134 ['magic_ls','magic_cd',...]"""
135 135
136 136 # FIXME. This needs a cleanup, in the way the magics list is built.
137 137
138 138 # magics in class definition
139 139 class_magic = lambda fn: fn.startswith('magic_') and \
140 140 callable(Magic.__dict__[fn])
141 141 # in instance namespace (run-time user additions)
142 142 inst_magic = lambda fn: fn.startswith('magic_') and \
143 143 callable(self.__dict__[fn])
144 144 # and bound magics by user (so they can access self):
145 145 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
146 146 callable(self.__class__.__dict__[fn])
147 147 magics = filter(class_magic,Magic.__dict__.keys()) + \
148 148 filter(inst_magic,self.__dict__.keys()) + \
149 149 filter(inst_bound_magic,self.__class__.__dict__.keys())
150 150 out = []
151 151 for fn in set(magics):
152 152 out.append(fn.replace('magic_','',1))
153 153 out.sort()
154 154 return out
155 155
156 156 def extract_input_slices(self,slices,raw=False):
157 157 """Return as a string a set of input history slices.
158 158
159 159 Inputs:
160 160
161 161 - slices: the set of slices is given as a list of strings (like
162 162 ['1','4:8','9'], since this function is for use by magic functions
163 163 which get their arguments as strings.
164 164
165 165 Optional inputs:
166 166
167 167 - raw(False): by default, the processed input is used. If this is
168 168 true, the raw input history is used instead.
169 169
170 170 Note that slices can be called with two notations:
171 171
172 172 N:M -> standard python form, means including items N...(M-1).
173 173
174 174 N-M -> include items N..M (closed endpoint)."""
175 175
176 176 if raw:
177 177 hist = self.shell.input_hist_raw
178 178 else:
179 179 hist = self.shell.input_hist
180 180
181 181 cmds = []
182 182 for chunk in slices:
183 183 if ':' in chunk:
184 184 ini,fin = map(int,chunk.split(':'))
185 185 elif '-' in chunk:
186 186 ini,fin = map(int,chunk.split('-'))
187 187 fin += 1
188 188 else:
189 189 ini = int(chunk)
190 190 fin = ini+1
191 191 cmds.append(hist[ini:fin])
192 192 return cmds
193 193
194 194 def _ofind(self, oname, namespaces=None):
195 195 """Find an object in the available namespaces.
196 196
197 197 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
198 198
199 199 Has special code to detect magic functions.
200 200 """
201 201 oname = oname.strip()
202 202 alias_ns = None
203 203 if namespaces is None:
204 204 # Namespaces to search in:
205 205 # Put them in a list. The order is important so that we
206 206 # find things in the same order that Python finds them.
207 207 namespaces = [ ('Interactive', self.shell.user_ns),
208 208 ('IPython internal', self.shell.internal_ns),
209 209 ('Python builtin', __builtin__.__dict__),
210 210 ('Alias', self.shell.alias_table),
211 211 ]
212 212 alias_ns = self.shell.alias_table
213 213
214 214 # initialize results to 'null'
215 215 found = False; obj = None; ospace = None; ds = None;
216 216 ismagic = False; isalias = False; parent = None
217 217
218 218 # We need to special-case 'print', which as of python2.6 registers as a
219 219 # function but should only be treated as one if print_function was
220 220 # loaded with a future import. In this case, just bail.
221 221 if (oname == 'print' and not (self.shell.compile.compiler.flags &
222 222 __future__.CO_FUTURE_PRINT_FUNCTION)):
223 223 return {'found':found, 'obj':obj, 'namespace':ospace,
224 224 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
225 225
226 226 # Look for the given name by splitting it in parts. If the head is
227 227 # found, then we look for all the remaining parts as members, and only
228 228 # declare success if we can find them all.
229 229 oname_parts = oname.split('.')
230 230 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
231 231 for nsname,ns in namespaces:
232 232 try:
233 233 obj = ns[oname_head]
234 234 except KeyError:
235 235 continue
236 236 else:
237 237 #print 'oname_rest:', oname_rest # dbg
238 238 for part in oname_rest:
239 239 try:
240 240 parent = obj
241 241 obj = getattr(obj,part)
242 242 except:
243 243 # Blanket except b/c some badly implemented objects
244 244 # allow __getattr__ to raise exceptions other than
245 245 # AttributeError, which then crashes IPython.
246 246 break
247 247 else:
248 248 # If we finish the for loop (no break), we got all members
249 249 found = True
250 250 ospace = nsname
251 251 if ns == alias_ns:
252 252 isalias = True
253 253 break # namespace loop
254 254
255 255 # Try to see if it's magic
256 256 if not found:
257 257 if oname.startswith(self.shell.ESC_MAGIC):
258 258 oname = oname[1:]
259 259 obj = getattr(self,'magic_'+oname,None)
260 260 if obj is not None:
261 261 found = True
262 262 ospace = 'IPython internal'
263 263 ismagic = True
264 264
265 265 # Last try: special-case some literals like '', [], {}, etc:
266 266 if not found and oname_head in ["''",'""','[]','{}','()']:
267 267 obj = eval(oname_head)
268 268 found = True
269 269 ospace = 'Interactive'
270 270
271 271 return {'found':found, 'obj':obj, 'namespace':ospace,
272 272 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
273 273
274 274 def arg_err(self,func):
275 275 """Print docstring if incorrect arguments were passed"""
276 276 print 'Error in arguments:'
277 277 print OInspect.getdoc(func)
278 278
279 279 def format_latex(self,strng):
280 280 """Format a string for latex inclusion."""
281 281
282 282 # Characters that need to be escaped for latex:
283 283 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
284 284 # Magic command names as headers:
285 285 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
286 286 re.MULTILINE)
287 287 # Magic commands
288 288 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
289 289 re.MULTILINE)
290 290 # Paragraph continue
291 291 par_re = re.compile(r'\\$',re.MULTILINE)
292 292
293 293 # The "\n" symbol
294 294 newline_re = re.compile(r'\\n')
295 295
296 296 # Now build the string for output:
297 297 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
298 298 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
299 299 strng)
300 300 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
301 301 strng = par_re.sub(r'\\\\',strng)
302 302 strng = escape_re.sub(r'\\\1',strng)
303 303 strng = newline_re.sub(r'\\textbackslash{}n',strng)
304 304 return strng
305 305
306 306 def format_screen(self,strng):
307 307 """Format a string for screen printing.
308 308
309 309 This removes some latex-type format codes."""
310 310 # Paragraph continue
311 311 par_re = re.compile(r'\\$',re.MULTILINE)
312 312 strng = par_re.sub('',strng)
313 313 return strng
314 314
315 315 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
316 316 """Parse options passed to an argument string.
317 317
318 318 The interface is similar to that of getopt(), but it returns back a
319 319 Struct with the options as keys and the stripped argument string still
320 320 as a string.
321 321
322 322 arg_str is quoted as a true sys.argv vector by using shlex.split.
323 323 This allows us to easily expand variables, glob files, quote
324 324 arguments, etc.
325 325
326 326 Options:
327 327 -mode: default 'string'. If given as 'list', the argument string is
328 328 returned as a list (split on whitespace) instead of a string.
329 329
330 330 -list_all: put all option values in lists. Normally only options
331 331 appearing more than once are put in a list.
332 332
333 333 -posix (True): whether to split the input line in POSIX mode or not,
334 334 as per the conventions outlined in the shlex module from the
335 335 standard library."""
336 336
337 337 # inject default options at the beginning of the input line
338 338 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
339 339 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
340 340
341 341 mode = kw.get('mode','string')
342 342 if mode not in ['string','list']:
343 343 raise ValueError,'incorrect mode given: %s' % mode
344 344 # Get options
345 345 list_all = kw.get('list_all',0)
346 346 posix = kw.get('posix',True)
347 347
348 348 # Check if we have more than one argument to warrant extra processing:
349 349 odict = {} # Dictionary with options
350 350 args = arg_str.split()
351 351 if len(args) >= 1:
352 352 # If the list of inputs only has 0 or 1 thing in it, there's no
353 353 # need to look for options
354 354 argv = arg_split(arg_str,posix)
355 355 # Do regular option processing
356 356 try:
357 357 opts,args = getopt(argv,opt_str,*long_opts)
358 358 except GetoptError,e:
359 359 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
360 360 " ".join(long_opts)))
361 361 for o,a in opts:
362 362 if o.startswith('--'):
363 363 o = o[2:]
364 364 else:
365 365 o = o[1:]
366 366 try:
367 367 odict[o].append(a)
368 368 except AttributeError:
369 369 odict[o] = [odict[o],a]
370 370 except KeyError:
371 371 if list_all:
372 372 odict[o] = [a]
373 373 else:
374 374 odict[o] = a
375 375
376 376 # Prepare opts,args for return
377 377 opts = Struct(odict)
378 378 if mode == 'string':
379 379 args = ' '.join(args)
380 380
381 381 return opts,args
382 382
383 383 #......................................................................
384 384 # And now the actual magic functions
385 385
386 386 # Functions for IPython shell work (vars,funcs, config, etc)
387 387 def magic_lsmagic(self, parameter_s = ''):
388 388 """List currently available magic functions."""
389 389 mesc = self.shell.ESC_MAGIC
390 390 print 'Available magic functions:\n'+mesc+\
391 391 (' '+mesc).join(self.lsmagic())
392 392 print '\n' + Magic.auto_status[self.shell.rc.automagic]
393 393 return None
394 394
395 395 def magic_magic(self, parameter_s = ''):
396 396 """Print information about the magic function system.
397 397
398 398 Supported formats: -latex, -brief, -rest
399 399 """
400 400
401 401 mode = ''
402 402 try:
403 403 if parameter_s.split()[0] == '-latex':
404 404 mode = 'latex'
405 405 if parameter_s.split()[0] == '-brief':
406 406 mode = 'brief'
407 407 if parameter_s.split()[0] == '-rest':
408 408 mode = 'rest'
409 409 rest_docs = []
410 410 except:
411 411 pass
412 412
413 413 magic_docs = []
414 414 for fname in self.lsmagic():
415 415 mname = 'magic_' + fname
416 416 for space in (Magic,self,self.__class__):
417 417 try:
418 418 fn = space.__dict__[mname]
419 419 except KeyError:
420 420 pass
421 421 else:
422 422 break
423 423 if mode == 'brief':
424 424 # only first line
425 425 if fn.__doc__:
426 426 fndoc = fn.__doc__.split('\n',1)[0]
427 427 else:
428 428 fndoc = 'No documentation'
429 429 else:
430 430 if fn.__doc__:
431 431 fndoc = fn.__doc__.rstrip()
432 432 else:
433 433 fndoc = 'No documentation'
434 434
435 435
436 436 if mode == 'rest':
437 437 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
438 438 fname,fndoc))
439 439
440 440 else:
441 441 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
442 442 fname,fndoc))
443 443
444 444 magic_docs = ''.join(magic_docs)
445 445
446 446 if mode == 'rest':
447 447 return "".join(rest_docs)
448 448
449 449 if mode == 'latex':
450 450 print self.format_latex(magic_docs)
451 451 return
452 452 else:
453 453 magic_docs = self.format_screen(magic_docs)
454 454 if mode == 'brief':
455 455 return magic_docs
456 456
457 457 outmsg = """
458 458 IPython's 'magic' functions
459 459 ===========================
460 460
461 461 The magic function system provides a series of functions which allow you to
462 462 control the behavior of IPython itself, plus a lot of system-type
463 463 features. All these functions are prefixed with a % character, but parameters
464 464 are given without parentheses or quotes.
465 465
466 466 NOTE: If you have 'automagic' enabled (via the command line option or with the
467 467 %automagic function), you don't need to type in the % explicitly. By default,
468 468 IPython ships with automagic on, so you should only rarely need the % escape.
469 469
470 470 Example: typing '%cd mydir' (without the quotes) changes you working directory
471 471 to 'mydir', if it exists.
472 472
473 473 You can define your own magic functions to extend the system. See the supplied
474 474 ipythonrc and example-magic.py files for details (in your ipython
475 475 configuration directory, typically $HOME/.ipython/).
476 476
477 477 You can also define your own aliased names for magic functions. In your
478 478 ipythonrc file, placing a line like:
479 479
480 480 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
481 481
482 482 will define %pf as a new name for %profile.
483 483
484 484 You can also call magics in code using the ipmagic() function, which IPython
485 485 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
486 486
487 487 For a list of the available magic functions, use %lsmagic. For a description
488 488 of any of them, type %magic_name?, e.g. '%cd?'.
489 489
490 490 Currently the magic system has the following functions:\n"""
491 491
492 492 mesc = self.shell.ESC_MAGIC
493 493 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
494 494 "\n\n%s%s\n\n%s" % (outmsg,
495 495 magic_docs,mesc,mesc,
496 496 (' '+mesc).join(self.lsmagic()),
497 497 Magic.auto_status[self.shell.rc.automagic] ) )
498 498
499 499 page(outmsg,screen_lines=self.shell.rc.screen_length)
500 500
501 501
502 502 def magic_autoindent(self, parameter_s = ''):
503 503 """Toggle autoindent on/off (if available)."""
504 504
505 505 self.shell.set_autoindent()
506 506 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
507 507
508 508
509 509 def magic_automagic(self, parameter_s = ''):
510 510 """Make magic functions callable without having to type the initial %.
511 511
512 512 Without argumentsl toggles on/off (when off, you must call it as
513 513 %automagic, of course). With arguments it sets the value, and you can
514 514 use any of (case insensitive):
515 515
516 516 - on,1,True: to activate
517 517
518 518 - off,0,False: to deactivate.
519 519
520 520 Note that magic functions have lowest priority, so if there's a
521 521 variable whose name collides with that of a magic fn, automagic won't
522 522 work for that function (you get the variable instead). However, if you
523 523 delete the variable (del var), the previously shadowed magic function
524 524 becomes visible to automagic again."""
525 525
526 526 rc = self.shell.rc
527 527 arg = parameter_s.lower()
528 528 if parameter_s in ('on','1','true'):
529 529 rc.automagic = True
530 530 elif parameter_s in ('off','0','false'):
531 531 rc.automagic = False
532 532 else:
533 533 rc.automagic = not rc.automagic
534 534 print '\n' + Magic.auto_status[rc.automagic]
535 535
536 536 @testdec.skip_doctest
537 537 def magic_autocall(self, parameter_s = ''):
538 538 """Make functions callable without having to type parentheses.
539 539
540 540 Usage:
541 541
542 542 %autocall [mode]
543 543
544 544 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
545 545 value is toggled on and off (remembering the previous state).
546 546
547 547 In more detail, these values mean:
548 548
549 549 0 -> fully disabled
550 550
551 551 1 -> active, but do not apply if there are no arguments on the line.
552 552
553 553 In this mode, you get:
554 554
555 555 In [1]: callable
556 556 Out[1]: <built-in function callable>
557 557
558 558 In [2]: callable 'hello'
559 559 ------> callable('hello')
560 560 Out[2]: False
561 561
562 562 2 -> Active always. Even if no arguments are present, the callable
563 563 object is called:
564 564
565 565 In [2]: float
566 566 ------> float()
567 567 Out[2]: 0.0
568 568
569 569 Note that even with autocall off, you can still use '/' at the start of
570 570 a line to treat the first argument on the command line as a function
571 571 and add parentheses to it:
572 572
573 573 In [8]: /str 43
574 574 ------> str(43)
575 575 Out[8]: '43'
576 576
577 577 # all-random (note for auto-testing)
578 578 """
579 579
580 580 rc = self.shell.rc
581 581
582 582 if parameter_s:
583 583 arg = int(parameter_s)
584 584 else:
585 585 arg = 'toggle'
586 586
587 587 if not arg in (0,1,2,'toggle'):
588 588 error('Valid modes: (0->Off, 1->Smart, 2->Full')
589 589 return
590 590
591 591 if arg in (0,1,2):
592 592 rc.autocall = arg
593 593 else: # toggle
594 594 if rc.autocall:
595 595 self._magic_state.autocall_save = rc.autocall
596 596 rc.autocall = 0
597 597 else:
598 598 try:
599 599 rc.autocall = self._magic_state.autocall_save
600 600 except AttributeError:
601 601 rc.autocall = self._magic_state.autocall_save = 1
602 602
603 603 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
604 604
605 605 def magic_system_verbose(self, parameter_s = ''):
606 606 """Set verbose printing of system calls.
607 607
608 608 If called without an argument, act as a toggle"""
609 609
610 610 if parameter_s:
611 611 val = bool(eval(parameter_s))
612 612 else:
613 613 val = None
614 614
615 615 self.shell.rc_set_toggle('system_verbose',val)
616 616 print "System verbose printing is:",\
617 617 ['OFF','ON'][self.shell.rc.system_verbose]
618 618
619 619
620 620 def magic_page(self, parameter_s=''):
621 621 """Pretty print the object and display it through a pager.
622 622
623 623 %page [options] OBJECT
624 624
625 625 If no object is given, use _ (last output).
626 626
627 627 Options:
628 628
629 629 -r: page str(object), don't pretty-print it."""
630 630
631 631 # After a function contributed by Olivier Aubert, slightly modified.
632 632
633 633 # Process options/args
634 634 opts,args = self.parse_options(parameter_s,'r')
635 635 raw = 'r' in opts
636 636
637 637 oname = args and args or '_'
638 638 info = self._ofind(oname)
639 639 if info['found']:
640 640 txt = (raw and str or pformat)( info['obj'] )
641 641 page(txt)
642 642 else:
643 643 print 'Object `%s` not found' % oname
644 644
645 645 def magic_profile(self, parameter_s=''):
646 646 """Print your currently active IPyhton profile."""
647 647 if self.shell.rc.profile:
648 648 printpl('Current IPython profile: $self.shell.rc.profile.')
649 649 else:
650 650 print 'No profile active.'
651 651
652 652 def magic_pinfo(self, parameter_s='', namespaces=None):
653 653 """Provide detailed information about an object.
654 654
655 655 '%pinfo object' is just a synonym for object? or ?object."""
656 656
657 657 #print 'pinfo par: <%s>' % parameter_s # dbg
658 658
659 659
660 660 # detail_level: 0 -> obj? , 1 -> obj??
661 661 detail_level = 0
662 662 # We need to detect if we got called as 'pinfo pinfo foo', which can
663 663 # happen if the user types 'pinfo foo?' at the cmd line.
664 664 pinfo,qmark1,oname,qmark2 = \
665 665 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
666 666 if pinfo or qmark1 or qmark2:
667 667 detail_level = 1
668 668 if "*" in oname:
669 669 self.magic_psearch(oname)
670 670 else:
671 671 self._inspect('pinfo', oname, detail_level=detail_level,
672 672 namespaces=namespaces)
673 673
674 674 def magic_pdef(self, parameter_s='', namespaces=None):
675 675 """Print the definition header for any callable object.
676 676
677 677 If the object is a class, print the constructor information."""
678 678 self._inspect('pdef',parameter_s, namespaces)
679 679
680 680 def magic_pdoc(self, parameter_s='', namespaces=None):
681 681 """Print the docstring for an object.
682 682
683 683 If the given object is a class, it will print both the class and the
684 684 constructor docstrings."""
685 685 self._inspect('pdoc',parameter_s, namespaces)
686 686
687 687 def magic_psource(self, parameter_s='', namespaces=None):
688 688 """Print (or run through pager) the source code for an object."""
689 689 self._inspect('psource',parameter_s, namespaces)
690 690
691 691 def magic_pfile(self, parameter_s=''):
692 692 """Print (or run through pager) the file where an object is defined.
693 693
694 694 The file opens at the line where the object definition begins. IPython
695 695 will honor the environment variable PAGER if set, and otherwise will
696 696 do its best to print the file in a convenient form.
697 697
698 698 If the given argument is not an object currently defined, IPython will
699 699 try to interpret it as a filename (automatically adding a .py extension
700 700 if needed). You can thus use %pfile as a syntax highlighting code
701 701 viewer."""
702 702
703 703 # first interpret argument as an object name
704 704 out = self._inspect('pfile',parameter_s)
705 705 # if not, try the input as a filename
706 706 if out == 'not found':
707 707 try:
708 708 filename = get_py_filename(parameter_s)
709 709 except IOError,msg:
710 710 print msg
711 711 return
712 712 page(self.shell.inspector.format(file(filename).read()))
713 713
714 714 def _inspect(self,meth,oname,namespaces=None,**kw):
715 715 """Generic interface to the inspector system.
716 716
717 717 This function is meant to be called by pdef, pdoc & friends."""
718 718
719 719 #oname = oname.strip()
720 720 #print '1- oname: <%r>' % oname # dbg
721 721 try:
722 722 oname = oname.strip().encode('ascii')
723 723 #print '2- oname: <%r>' % oname # dbg
724 724 except UnicodeEncodeError:
725 725 print 'Python identifiers can only contain ascii characters.'
726 726 return 'not found'
727 727
728 728 info = Struct(self._ofind(oname, namespaces))
729 729
730 730 if info.found:
731 731 try:
732 732 IPython.generics.inspect_object(info.obj)
733 733 return
734 734 except IPython.ipapi.TryNext:
735 735 pass
736 736 # Get the docstring of the class property if it exists.
737 737 path = oname.split('.')
738 738 root = '.'.join(path[:-1])
739 739 if info.parent is not None:
740 740 try:
741 741 target = getattr(info.parent, '__class__')
742 742 # The object belongs to a class instance.
743 743 try:
744 744 target = getattr(target, path[-1])
745 745 # The class defines the object.
746 746 if isinstance(target, property):
747 747 oname = root + '.__class__.' + path[-1]
748 748 info = Struct(self._ofind(oname))
749 749 except AttributeError: pass
750 750 except AttributeError: pass
751 751
752 752 pmethod = getattr(self.shell.inspector,meth)
753 753 formatter = info.ismagic and self.format_screen or None
754 754 if meth == 'pdoc':
755 755 pmethod(info.obj,oname,formatter)
756 756 elif meth == 'pinfo':
757 757 pmethod(info.obj,oname,formatter,info,**kw)
758 758 else:
759 759 pmethod(info.obj,oname)
760 760 else:
761 761 print 'Object `%s` not found.' % oname
762 762 return 'not found' # so callers can take other action
763 763
764 764 def magic_psearch(self, parameter_s=''):
765 765 """Search for object in namespaces by wildcard.
766 766
767 767 %psearch [options] PATTERN [OBJECT TYPE]
768 768
769 769 Note: ? can be used as a synonym for %psearch, at the beginning or at
770 770 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
771 771 rest of the command line must be unchanged (options come first), so
772 772 for example the following forms are equivalent
773 773
774 774 %psearch -i a* function
775 775 -i a* function?
776 776 ?-i a* function
777 777
778 778 Arguments:
779 779
780 780 PATTERN
781 781
782 782 where PATTERN is a string containing * as a wildcard similar to its
783 783 use in a shell. The pattern is matched in all namespaces on the
784 784 search path. By default objects starting with a single _ are not
785 785 matched, many IPython generated objects have a single
786 786 underscore. The default is case insensitive matching. Matching is
787 787 also done on the attributes of objects and not only on the objects
788 788 in a module.
789 789
790 790 [OBJECT TYPE]
791 791
792 792 Is the name of a python type from the types module. The name is
793 793 given in lowercase without the ending type, ex. StringType is
794 794 written string. By adding a type here only objects matching the
795 795 given type are matched. Using all here makes the pattern match all
796 796 types (this is the default).
797 797
798 798 Options:
799 799
800 800 -a: makes the pattern match even objects whose names start with a
801 801 single underscore. These names are normally ommitted from the
802 802 search.
803 803
804 804 -i/-c: make the pattern case insensitive/sensitive. If neither of
805 805 these options is given, the default is read from your ipythonrc
806 806 file. The option name which sets this value is
807 807 'wildcards_case_sensitive'. If this option is not specified in your
808 808 ipythonrc file, IPython's internal default is to do a case sensitive
809 809 search.
810 810
811 811 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
812 812 specifiy can be searched in any of the following namespaces:
813 813 'builtin', 'user', 'user_global','internal', 'alias', where
814 814 'builtin' and 'user' are the search defaults. Note that you should
815 815 not use quotes when specifying namespaces.
816 816
817 817 'Builtin' contains the python module builtin, 'user' contains all
818 818 user data, 'alias' only contain the shell aliases and no python
819 819 objects, 'internal' contains objects used by IPython. The
820 820 'user_global' namespace is only used by embedded IPython instances,
821 821 and it contains module-level globals. You can add namespaces to the
822 822 search with -s or exclude them with -e (these options can be given
823 823 more than once).
824 824
825 825 Examples:
826 826
827 827 %psearch a* -> objects beginning with an a
828 828 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
829 829 %psearch a* function -> all functions beginning with an a
830 830 %psearch re.e* -> objects beginning with an e in module re
831 831 %psearch r*.e* -> objects that start with e in modules starting in r
832 832 %psearch r*.* string -> all strings in modules beginning with r
833 833
834 834 Case sensitve search:
835 835
836 836 %psearch -c a* list all object beginning with lower case a
837 837
838 838 Show objects beginning with a single _:
839 839
840 840 %psearch -a _* list objects beginning with a single underscore"""
841 841 try:
842 842 parameter_s = parameter_s.encode('ascii')
843 843 except UnicodeEncodeError:
844 844 print 'Python identifiers can only contain ascii characters.'
845 845 return
846 846
847 847 # default namespaces to be searched
848 848 def_search = ['user','builtin']
849 849
850 850 # Process options/args
851 851 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
852 852 opt = opts.get
853 853 shell = self.shell
854 854 psearch = shell.inspector.psearch
855 855
856 856 # select case options
857 857 if opts.has_key('i'):
858 858 ignore_case = True
859 859 elif opts.has_key('c'):
860 860 ignore_case = False
861 861 else:
862 862 ignore_case = not shell.rc.wildcards_case_sensitive
863 863
864 864 # Build list of namespaces to search from user options
865 865 def_search.extend(opt('s',[]))
866 866 ns_exclude = ns_exclude=opt('e',[])
867 867 ns_search = [nm for nm in def_search if nm not in ns_exclude]
868 868
869 869 # Call the actual search
870 870 try:
871 871 psearch(args,shell.ns_table,ns_search,
872 872 show_all=opt('a'),ignore_case=ignore_case)
873 873 except:
874 874 shell.showtraceback()
875 875
876 876 def magic_who_ls(self, parameter_s=''):
877 877 """Return a sorted list of all interactive variables.
878 878
879 879 If arguments are given, only variables of types matching these
880 880 arguments are returned."""
881 881
882 882 user_ns = self.shell.user_ns
883 883 internal_ns = self.shell.internal_ns
884 884 user_config_ns = self.shell.user_config_ns
885 885 out = []
886 886 typelist = parameter_s.split()
887 887
888 888 for i in user_ns:
889 889 if not (i.startswith('_') or i.startswith('_i')) \
890 890 and not (i in internal_ns or i in user_config_ns):
891 891 if typelist:
892 892 if type(user_ns[i]).__name__ in typelist:
893 893 out.append(i)
894 894 else:
895 895 out.append(i)
896 896 out.sort()
897 897 return out
898 898
899 899 def magic_who(self, parameter_s=''):
900 900 """Print all interactive variables, with some minimal formatting.
901 901
902 902 If any arguments are given, only variables whose type matches one of
903 903 these are printed. For example:
904 904
905 905 %who function str
906 906
907 907 will only list functions and strings, excluding all other types of
908 908 variables. To find the proper type names, simply use type(var) at a
909 909 command line to see how python prints type names. For example:
910 910
911 911 In [1]: type('hello')\\
912 912 Out[1]: <type 'str'>
913 913
914 914 indicates that the type name for strings is 'str'.
915 915
916 916 %who always excludes executed names loaded through your configuration
917 917 file and things which are internal to IPython.
918 918
919 919 This is deliberate, as typically you may load many modules and the
920 920 purpose of %who is to show you only what you've manually defined."""
921 921
922 922 varlist = self.magic_who_ls(parameter_s)
923 923 if not varlist:
924 924 if parameter_s:
925 925 print 'No variables match your requested type.'
926 926 else:
927 927 print 'Interactive namespace is empty.'
928 928 return
929 929
930 930 # if we have variables, move on...
931 931 count = 0
932 932 for i in varlist:
933 933 print i+'\t',
934 934 count += 1
935 935 if count > 8:
936 936 count = 0
937 937 print
938 938 print
939 939
940 940 def magic_whos(self, parameter_s=''):
941 941 """Like %who, but gives some extra information about each variable.
942 942
943 943 The same type filtering of %who can be applied here.
944 944
945 945 For all variables, the type is printed. Additionally it prints:
946 946
947 947 - For {},[],(): their length.
948 948
949 949 - For numpy and Numeric arrays, a summary with shape, number of
950 950 elements, typecode and size in memory.
951 951
952 952 - Everything else: a string representation, snipping their middle if
953 953 too long."""
954 954
955 955 varnames = self.magic_who_ls(parameter_s)
956 956 if not varnames:
957 957 if parameter_s:
958 958 print 'No variables match your requested type.'
959 959 else:
960 960 print 'Interactive namespace is empty.'
961 961 return
962 962
963 963 # if we have variables, move on...
964 964
965 965 # for these types, show len() instead of data:
966 966 seq_types = [types.DictType,types.ListType,types.TupleType]
967 967
968 968 # for numpy/Numeric arrays, display summary info
969 969 try:
970 970 import numpy
971 971 except ImportError:
972 972 ndarray_type = None
973 973 else:
974 974 ndarray_type = numpy.ndarray.__name__
975 975 try:
976 976 import Numeric
977 977 except ImportError:
978 978 array_type = None
979 979 else:
980 980 array_type = Numeric.ArrayType.__name__
981 981
982 982 # Find all variable names and types so we can figure out column sizes
983 983 def get_vars(i):
984 984 return self.shell.user_ns[i]
985 985
986 986 # some types are well known and can be shorter
987 987 abbrevs = {'IPython.macro.Macro' : 'Macro'}
988 988 def type_name(v):
989 989 tn = type(v).__name__
990 990 return abbrevs.get(tn,tn)
991 991
992 992 varlist = map(get_vars,varnames)
993 993
994 994 typelist = []
995 995 for vv in varlist:
996 996 tt = type_name(vv)
997 997
998 998 if tt=='instance':
999 999 typelist.append( abbrevs.get(str(vv.__class__),
1000 1000 str(vv.__class__)))
1001 1001 else:
1002 1002 typelist.append(tt)
1003 1003
1004 1004 # column labels and # of spaces as separator
1005 1005 varlabel = 'Variable'
1006 1006 typelabel = 'Type'
1007 1007 datalabel = 'Data/Info'
1008 1008 colsep = 3
1009 1009 # variable format strings
1010 1010 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1011 1011 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1012 1012 aformat = "%s: %s elems, type `%s`, %s bytes"
1013 1013 # find the size of the columns to format the output nicely
1014 1014 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1015 1015 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1016 1016 # table header
1017 1017 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1018 1018 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1019 1019 # and the table itself
1020 1020 kb = 1024
1021 1021 Mb = 1048576 # kb**2
1022 1022 for vname,var,vtype in zip(varnames,varlist,typelist):
1023 1023 print itpl(vformat),
1024 1024 if vtype in seq_types:
1025 1025 print len(var)
1026 1026 elif vtype in [array_type,ndarray_type]:
1027 1027 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1028 1028 if vtype==ndarray_type:
1029 1029 # numpy
1030 1030 vsize = var.size
1031 1031 vbytes = vsize*var.itemsize
1032 1032 vdtype = var.dtype
1033 1033 else:
1034 1034 # Numeric
1035 1035 vsize = Numeric.size(var)
1036 1036 vbytes = vsize*var.itemsize()
1037 1037 vdtype = var.typecode()
1038 1038
1039 1039 if vbytes < 100000:
1040 1040 print aformat % (vshape,vsize,vdtype,vbytes)
1041 1041 else:
1042 1042 print aformat % (vshape,vsize,vdtype,vbytes),
1043 1043 if vbytes < Mb:
1044 1044 print '(%s kb)' % (vbytes/kb,)
1045 1045 else:
1046 1046 print '(%s Mb)' % (vbytes/Mb,)
1047 1047 else:
1048 1048 try:
1049 1049 vstr = str(var)
1050 1050 except UnicodeEncodeError:
1051 1051 vstr = unicode(var).encode(sys.getdefaultencoding(),
1052 1052 'backslashreplace')
1053 1053 vstr = vstr.replace('\n','\\n')
1054 1054 if len(vstr) < 50:
1055 1055 print vstr
1056 1056 else:
1057 1057 printpl(vfmt_short)
1058 1058
1059 1059 def magic_reset(self, parameter_s=''):
1060 1060 """Resets the namespace by removing all names defined by the user.
1061 1061
1062 1062 Input/Output history are left around in case you need them.
1063 1063
1064 1064 Parameters
1065 1065 ----------
1066 1066 -f : force reset without asking for confirmation.
1067 1067
1068 1068 Examples
1069 1069 --------
1070 1070 In [6]: a = 1
1071 1071
1072 1072 In [7]: a
1073 1073 Out[7]: 1
1074 1074
1075 1075 In [8]: 'a' in _ip.user_ns
1076 1076 Out[8]: True
1077 1077
1078 1078 In [9]: %reset -f
1079 1079
1080 1080 In [10]: 'a' in _ip.user_ns
1081 1081 Out[10]: False
1082 1082 """
1083 1083
1084 1084 if parameter_s == '-f':
1085 1085 ans = True
1086 1086 else:
1087 1087 ans = self.shell.ask_yes_no(
1088 1088 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1089 1089 if not ans:
1090 1090 print 'Nothing done.'
1091 1091 return
1092 1092 user_ns = self.shell.user_ns
1093 1093 for i in self.magic_who_ls():
1094 1094 del(user_ns[i])
1095 1095
1096 1096 # Also flush the private list of module references kept for script
1097 1097 # execution protection
1098 1098 self.shell.clear_main_mod_cache()
1099 1099
1100 1100 def magic_logstart(self,parameter_s=''):
1101 1101 """Start logging anywhere in a session.
1102 1102
1103 1103 %logstart [-o|-r|-t] [log_name [log_mode]]
1104 1104
1105 1105 If no name is given, it defaults to a file named 'ipython_log.py' in your
1106 1106 current directory, in 'rotate' mode (see below).
1107 1107
1108 1108 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1109 1109 history up to that point and then continues logging.
1110 1110
1111 1111 %logstart takes a second optional parameter: logging mode. This can be one
1112 1112 of (note that the modes are given unquoted):\\
1113 1113 append: well, that says it.\\
1114 1114 backup: rename (if exists) to name~ and start name.\\
1115 1115 global: single logfile in your home dir, appended to.\\
1116 1116 over : overwrite existing log.\\
1117 1117 rotate: create rotating logs name.1~, name.2~, etc.
1118 1118
1119 1119 Options:
1120 1120
1121 1121 -o: log also IPython's output. In this mode, all commands which
1122 1122 generate an Out[NN] prompt are recorded to the logfile, right after
1123 1123 their corresponding input line. The output lines are always
1124 1124 prepended with a '#[Out]# ' marker, so that the log remains valid
1125 1125 Python code.
1126 1126
1127 1127 Since this marker is always the same, filtering only the output from
1128 1128 a log is very easy, using for example a simple awk call:
1129 1129
1130 1130 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1131 1131
1132 1132 -r: log 'raw' input. Normally, IPython's logs contain the processed
1133 1133 input, so that user lines are logged in their final form, converted
1134 1134 into valid Python. For example, %Exit is logged as
1135 1135 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1136 1136 exactly as typed, with no transformations applied.
1137 1137
1138 1138 -t: put timestamps before each input line logged (these are put in
1139 1139 comments)."""
1140 1140
1141 1141 opts,par = self.parse_options(parameter_s,'ort')
1142 1142 log_output = 'o' in opts
1143 1143 log_raw_input = 'r' in opts
1144 1144 timestamp = 't' in opts
1145 1145
1146 1146 rc = self.shell.rc
1147 1147 logger = self.shell.logger
1148 1148
1149 1149 # if no args are given, the defaults set in the logger constructor by
1150 1150 # ipytohn remain valid
1151 1151 if par:
1152 1152 try:
1153 1153 logfname,logmode = par.split()
1154 1154 except:
1155 1155 logfname = par
1156 1156 logmode = 'backup'
1157 1157 else:
1158 1158 logfname = logger.logfname
1159 1159 logmode = logger.logmode
1160 1160 # put logfname into rc struct as if it had been called on the command
1161 1161 # line, so it ends up saved in the log header Save it in case we need
1162 1162 # to restore it...
1163 1163 old_logfile = rc.opts.get('logfile','')
1164 1164 if logfname:
1165 1165 logfname = os.path.expanduser(logfname)
1166 1166 rc.opts.logfile = logfname
1167 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1167 loghead = self.shell.loghead_tpl % (sys.stdin.encoding, rc.opts, rc.args)
1168 1168 try:
1169 1169 started = logger.logstart(logfname,loghead,logmode,
1170 1170 log_output,timestamp,log_raw_input)
1171 1171 except:
1172 1172 rc.opts.logfile = old_logfile
1173 1173 warn("Couldn't start log: %s" % sys.exc_info()[1])
1174 1174 else:
1175 1175 # log input history up to this point, optionally interleaving
1176 1176 # output if requested
1177 1177
1178 1178 if timestamp:
1179 1179 # disable timestamping for the previous history, since we've
1180 1180 # lost those already (no time machine here).
1181 1181 logger.timestamp = False
1182 1182
1183 1183 if log_raw_input:
1184 1184 input_hist = self.shell.input_hist_raw
1185 1185 else:
1186 1186 input_hist = self.shell.input_hist
1187 1187
1188 1188 if log_output:
1189 1189 log_write = logger.log_write
1190 1190 output_hist = self.shell.output_hist
1191 1191 for n in range(1,len(input_hist)-1):
1192 1192 log_write(input_hist[n].rstrip())
1193 1193 if n in output_hist:
1194 1194 log_write(repr(output_hist[n]),'output')
1195 1195 else:
1196 1196 logger.log_write(input_hist[1:])
1197 1197 if timestamp:
1198 1198 # re-enable timestamping
1199 1199 logger.timestamp = True
1200 1200
1201 1201 print ('Activating auto-logging. '
1202 1202 'Current session state plus future input saved.')
1203 1203 logger.logstate()
1204 1204
1205 1205 def magic_logstop(self,parameter_s=''):
1206 1206 """Fully stop logging and close log file.
1207 1207
1208 1208 In order to start logging again, a new %logstart call needs to be made,
1209 1209 possibly (though not necessarily) with a new filename, mode and other
1210 1210 options."""
1211 1211 self.logger.logstop()
1212 1212
1213 1213 def magic_logoff(self,parameter_s=''):
1214 1214 """Temporarily stop logging.
1215 1215
1216 1216 You must have previously started logging."""
1217 1217 self.shell.logger.switch_log(0)
1218 1218
1219 1219 def magic_logon(self,parameter_s=''):
1220 1220 """Restart logging.
1221 1221
1222 1222 This function is for restarting logging which you've temporarily
1223 1223 stopped with %logoff. For starting logging for the first time, you
1224 1224 must use the %logstart function, which allows you to specify an
1225 1225 optional log filename."""
1226 1226
1227 1227 self.shell.logger.switch_log(1)
1228 1228
1229 1229 def magic_logstate(self,parameter_s=''):
1230 1230 """Print the status of the logging system."""
1231 1231
1232 1232 self.shell.logger.logstate()
1233 1233
1234 1234 def magic_pdb(self, parameter_s=''):
1235 1235 """Control the automatic calling of the pdb interactive debugger.
1236 1236
1237 1237 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1238 1238 argument it works as a toggle.
1239 1239
1240 1240 When an exception is triggered, IPython can optionally call the
1241 1241 interactive pdb debugger after the traceback printout. %pdb toggles
1242 1242 this feature on and off.
1243 1243
1244 1244 The initial state of this feature is set in your ipythonrc
1245 1245 configuration file (the variable is called 'pdb').
1246 1246
1247 1247 If you want to just activate the debugger AFTER an exception has fired,
1248 1248 without having to type '%pdb on' and rerunning your code, you can use
1249 1249 the %debug magic."""
1250 1250
1251 1251 par = parameter_s.strip().lower()
1252 1252
1253 1253 if par:
1254 1254 try:
1255 1255 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1256 1256 except KeyError:
1257 1257 print ('Incorrect argument. Use on/1, off/0, '
1258 1258 'or nothing for a toggle.')
1259 1259 return
1260 1260 else:
1261 1261 # toggle
1262 1262 new_pdb = not self.shell.call_pdb
1263 1263
1264 1264 # set on the shell
1265 1265 self.shell.call_pdb = new_pdb
1266 1266 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1267 1267
1268 1268 def magic_debug(self, parameter_s=''):
1269 1269 """Activate the interactive debugger in post-mortem mode.
1270 1270
1271 1271 If an exception has just occurred, this lets you inspect its stack
1272 1272 frames interactively. Note that this will always work only on the last
1273 1273 traceback that occurred, so you must call this quickly after an
1274 1274 exception that you wish to inspect has fired, because if another one
1275 1275 occurs, it clobbers the previous one.
1276 1276
1277 1277 If you want IPython to automatically do this on every exception, see
1278 1278 the %pdb magic for more details.
1279 1279 """
1280 1280
1281 1281 self.shell.debugger(force=True)
1282 1282
1283 1283 @testdec.skip_doctest
1284 1284 def magic_prun(self, parameter_s ='',user_mode=1,
1285 1285 opts=None,arg_lst=None,prog_ns=None):
1286 1286
1287 1287 """Run a statement through the python code profiler.
1288 1288
1289 1289 Usage:
1290 1290 %prun [options] statement
1291 1291
1292 1292 The given statement (which doesn't require quote marks) is run via the
1293 1293 python profiler in a manner similar to the profile.run() function.
1294 1294 Namespaces are internally managed to work correctly; profile.run
1295 1295 cannot be used in IPython because it makes certain assumptions about
1296 1296 namespaces which do not hold under IPython.
1297 1297
1298 1298 Options:
1299 1299
1300 1300 -l <limit>: you can place restrictions on what or how much of the
1301 1301 profile gets printed. The limit value can be:
1302 1302
1303 1303 * A string: only information for function names containing this string
1304 1304 is printed.
1305 1305
1306 1306 * An integer: only these many lines are printed.
1307 1307
1308 1308 * A float (between 0 and 1): this fraction of the report is printed
1309 1309 (for example, use a limit of 0.4 to see the topmost 40% only).
1310 1310
1311 1311 You can combine several limits with repeated use of the option. For
1312 1312 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1313 1313 information about class constructors.
1314 1314
1315 1315 -r: return the pstats.Stats object generated by the profiling. This
1316 1316 object has all the information about the profile in it, and you can
1317 1317 later use it for further analysis or in other functions.
1318 1318
1319 1319 -s <key>: sort profile by given key. You can provide more than one key
1320 1320 by using the option several times: '-s key1 -s key2 -s key3...'. The
1321 1321 default sorting key is 'time'.
1322 1322
1323 1323 The following is copied verbatim from the profile documentation
1324 1324 referenced below:
1325 1325
1326 1326 When more than one key is provided, additional keys are used as
1327 1327 secondary criteria when the there is equality in all keys selected
1328 1328 before them.
1329 1329
1330 1330 Abbreviations can be used for any key names, as long as the
1331 1331 abbreviation is unambiguous. The following are the keys currently
1332 1332 defined:
1333 1333
1334 1334 Valid Arg Meaning
1335 1335 "calls" call count
1336 1336 "cumulative" cumulative time
1337 1337 "file" file name
1338 1338 "module" file name
1339 1339 "pcalls" primitive call count
1340 1340 "line" line number
1341 1341 "name" function name
1342 1342 "nfl" name/file/line
1343 1343 "stdname" standard name
1344 1344 "time" internal time
1345 1345
1346 1346 Note that all sorts on statistics are in descending order (placing
1347 1347 most time consuming items first), where as name, file, and line number
1348 1348 searches are in ascending order (i.e., alphabetical). The subtle
1349 1349 distinction between "nfl" and "stdname" is that the standard name is a
1350 1350 sort of the name as printed, which means that the embedded line
1351 1351 numbers get compared in an odd way. For example, lines 3, 20, and 40
1352 1352 would (if the file names were the same) appear in the string order
1353 1353 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1354 1354 line numbers. In fact, sort_stats("nfl") is the same as
1355 1355 sort_stats("name", "file", "line").
1356 1356
1357 1357 -T <filename>: save profile results as shown on screen to a text
1358 1358 file. The profile is still shown on screen.
1359 1359
1360 1360 -D <filename>: save (via dump_stats) profile statistics to given
1361 1361 filename. This data is in a format understod by the pstats module, and
1362 1362 is generated by a call to the dump_stats() method of profile
1363 1363 objects. The profile is still shown on screen.
1364 1364
1365 1365 If you want to run complete programs under the profiler's control, use
1366 1366 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1367 1367 contains profiler specific options as described here.
1368 1368
1369 1369 You can read the complete documentation for the profile module with::
1370 1370
1371 1371 In [1]: import profile; profile.help()
1372 1372 """
1373 1373
1374 1374 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1375 1375 # protect user quote marks
1376 1376 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1377 1377
1378 1378 if user_mode: # regular user call
1379 1379 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1380 1380 list_all=1)
1381 1381 namespace = self.shell.user_ns
1382 1382 else: # called to run a program by %run -p
1383 1383 try:
1384 1384 filename = get_py_filename(arg_lst[0])
1385 1385 except IOError,msg:
1386 1386 error(msg)
1387 1387 return
1388 1388
1389 1389 arg_str = 'execfile(filename,prog_ns)'
1390 1390 namespace = locals()
1391 1391
1392 1392 opts.merge(opts_def)
1393 1393
1394 1394 prof = profile.Profile()
1395 1395 try:
1396 1396 prof = prof.runctx(arg_str,namespace,namespace)
1397 1397 sys_exit = ''
1398 1398 except SystemExit:
1399 1399 sys_exit = """*** SystemExit exception caught in code being profiled."""
1400 1400
1401 1401 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1402 1402
1403 1403 lims = opts.l
1404 1404 if lims:
1405 1405 lims = [] # rebuild lims with ints/floats/strings
1406 1406 for lim in opts.l:
1407 1407 try:
1408 1408 lims.append(int(lim))
1409 1409 except ValueError:
1410 1410 try:
1411 1411 lims.append(float(lim))
1412 1412 except ValueError:
1413 1413 lims.append(lim)
1414 1414
1415 1415 # Trap output.
1416 1416 stdout_trap = StringIO()
1417 1417
1418 1418 if hasattr(stats,'stream'):
1419 1419 # In newer versions of python, the stats object has a 'stream'
1420 1420 # attribute to write into.
1421 1421 stats.stream = stdout_trap
1422 1422 stats.print_stats(*lims)
1423 1423 else:
1424 1424 # For older versions, we manually redirect stdout during printing
1425 1425 sys_stdout = sys.stdout
1426 1426 try:
1427 1427 sys.stdout = stdout_trap
1428 1428 stats.print_stats(*lims)
1429 1429 finally:
1430 1430 sys.stdout = sys_stdout
1431 1431
1432 1432 output = stdout_trap.getvalue()
1433 1433 output = output.rstrip()
1434 1434
1435 1435 page(output,screen_lines=self.shell.rc.screen_length)
1436 1436 print sys_exit,
1437 1437
1438 1438 dump_file = opts.D[0]
1439 1439 text_file = opts.T[0]
1440 1440 if dump_file:
1441 1441 prof.dump_stats(dump_file)
1442 1442 print '\n*** Profile stats marshalled to file',\
1443 1443 `dump_file`+'.',sys_exit
1444 1444 if text_file:
1445 1445 pfile = file(text_file,'w')
1446 1446 pfile.write(output)
1447 1447 pfile.close()
1448 1448 print '\n*** Profile printout saved to text file',\
1449 1449 `text_file`+'.',sys_exit
1450 1450
1451 1451 if opts.has_key('r'):
1452 1452 return stats
1453 1453 else:
1454 1454 return None
1455 1455
1456 1456 @testdec.skip_doctest
1457 1457 def magic_run(self, parameter_s ='',runner=None,
1458 1458 file_finder=get_py_filename):
1459 1459 """Run the named file inside IPython as a program.
1460 1460
1461 1461 Usage:\\
1462 1462 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1463 1463
1464 1464 Parameters after the filename are passed as command-line arguments to
1465 1465 the program (put in sys.argv). Then, control returns to IPython's
1466 1466 prompt.
1467 1467
1468 1468 This is similar to running at a system prompt:\\
1469 1469 $ python file args\\
1470 1470 but with the advantage of giving you IPython's tracebacks, and of
1471 1471 loading all variables into your interactive namespace for further use
1472 1472 (unless -p is used, see below).
1473 1473
1474 1474 The file is executed in a namespace initially consisting only of
1475 1475 __name__=='__main__' and sys.argv constructed as indicated. It thus
1476 1476 sees its environment as if it were being run as a stand-alone program
1477 1477 (except for sharing global objects such as previously imported
1478 1478 modules). But after execution, the IPython interactive namespace gets
1479 1479 updated with all variables defined in the program (except for __name__
1480 1480 and sys.argv). This allows for very convenient loading of code for
1481 1481 interactive work, while giving each program a 'clean sheet' to run in.
1482 1482
1483 1483 Options:
1484 1484
1485 1485 -n: __name__ is NOT set to '__main__', but to the running file's name
1486 1486 without extension (as python does under import). This allows running
1487 1487 scripts and reloading the definitions in them without calling code
1488 1488 protected by an ' if __name__ == "__main__" ' clause.
1489 1489
1490 1490 -i: run the file in IPython's namespace instead of an empty one. This
1491 1491 is useful if you are experimenting with code written in a text editor
1492 1492 which depends on variables defined interactively.
1493 1493
1494 1494 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1495 1495 being run. This is particularly useful if IPython is being used to
1496 1496 run unittests, which always exit with a sys.exit() call. In such
1497 1497 cases you are interested in the output of the test results, not in
1498 1498 seeing a traceback of the unittest module.
1499 1499
1500 1500 -t: print timing information at the end of the run. IPython will give
1501 1501 you an estimated CPU time consumption for your script, which under
1502 1502 Unix uses the resource module to avoid the wraparound problems of
1503 1503 time.clock(). Under Unix, an estimate of time spent on system tasks
1504 1504 is also given (for Windows platforms this is reported as 0.0).
1505 1505
1506 1506 If -t is given, an additional -N<N> option can be given, where <N>
1507 1507 must be an integer indicating how many times you want the script to
1508 1508 run. The final timing report will include total and per run results.
1509 1509
1510 1510 For example (testing the script uniq_stable.py):
1511 1511
1512 1512 In [1]: run -t uniq_stable
1513 1513
1514 1514 IPython CPU timings (estimated):\\
1515 1515 User : 0.19597 s.\\
1516 1516 System: 0.0 s.\\
1517 1517
1518 1518 In [2]: run -t -N5 uniq_stable
1519 1519
1520 1520 IPython CPU timings (estimated):\\
1521 1521 Total runs performed: 5\\
1522 1522 Times : Total Per run\\
1523 1523 User : 0.910862 s, 0.1821724 s.\\
1524 1524 System: 0.0 s, 0.0 s.
1525 1525
1526 1526 -d: run your program under the control of pdb, the Python debugger.
1527 1527 This allows you to execute your program step by step, watch variables,
1528 1528 etc. Internally, what IPython does is similar to calling:
1529 1529
1530 1530 pdb.run('execfile("YOURFILENAME")')
1531 1531
1532 1532 with a breakpoint set on line 1 of your file. You can change the line
1533 1533 number for this automatic breakpoint to be <N> by using the -bN option
1534 1534 (where N must be an integer). For example:
1535 1535
1536 1536 %run -d -b40 myscript
1537 1537
1538 1538 will set the first breakpoint at line 40 in myscript.py. Note that
1539 1539 the first breakpoint must be set on a line which actually does
1540 1540 something (not a comment or docstring) for it to stop execution.
1541 1541
1542 1542 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1543 1543 first enter 'c' (without qoutes) to start execution up to the first
1544 1544 breakpoint.
1545 1545
1546 1546 Entering 'help' gives information about the use of the debugger. You
1547 1547 can easily see pdb's full documentation with "import pdb;pdb.help()"
1548 1548 at a prompt.
1549 1549
1550 1550 -p: run program under the control of the Python profiler module (which
1551 1551 prints a detailed report of execution times, function calls, etc).
1552 1552
1553 1553 You can pass other options after -p which affect the behavior of the
1554 1554 profiler itself. See the docs for %prun for details.
1555 1555
1556 1556 In this mode, the program's variables do NOT propagate back to the
1557 1557 IPython interactive namespace (because they remain in the namespace
1558 1558 where the profiler executes them).
1559 1559
1560 1560 Internally this triggers a call to %prun, see its documentation for
1561 1561 details on the options available specifically for profiling.
1562 1562
1563 1563 There is one special usage for which the text above doesn't apply:
1564 1564 if the filename ends with .ipy, the file is run as ipython script,
1565 1565 just as if the commands were written on IPython prompt.
1566 1566 """
1567 1567
1568 1568 # get arguments and set sys.argv for program to be run.
1569 1569 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1570 1570 mode='list',list_all=1)
1571 1571
1572 1572 try:
1573 1573 filename = file_finder(arg_lst[0])
1574 1574 except IndexError:
1575 1575 warn('you must provide at least a filename.')
1576 1576 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1577 1577 return
1578 1578 except IOError,msg:
1579 1579 error(msg)
1580 1580 return
1581 1581
1582 1582 if filename.lower().endswith('.ipy'):
1583 1583 self.api.runlines(open(filename).read())
1584 1584 return
1585 1585
1586 1586 # Control the response to exit() calls made by the script being run
1587 1587 exit_ignore = opts.has_key('e')
1588 1588
1589 1589 # Make sure that the running script gets a proper sys.argv as if it
1590 1590 # were run from a system shell.
1591 1591 save_argv = sys.argv # save it for later restoring
1592 1592 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1593 1593
1594 1594 if opts.has_key('i'):
1595 1595 # Run in user's interactive namespace
1596 1596 prog_ns = self.shell.user_ns
1597 1597 __name__save = self.shell.user_ns['__name__']
1598 1598 prog_ns['__name__'] = '__main__'
1599 1599 main_mod = self.shell.new_main_mod(prog_ns)
1600 1600 else:
1601 1601 # Run in a fresh, empty namespace
1602 1602 if opts.has_key('n'):
1603 1603 name = os.path.splitext(os.path.basename(filename))[0]
1604 1604 else:
1605 1605 name = '__main__'
1606 1606
1607 1607 main_mod = self.shell.new_main_mod()
1608 1608 prog_ns = main_mod.__dict__
1609 1609 prog_ns['__name__'] = name
1610 1610
1611 1611 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1612 1612 # set the __file__ global in the script's namespace
1613 1613 prog_ns['__file__'] = filename
1614 1614
1615 1615 # pickle fix. See iplib for an explanation. But we need to make sure
1616 1616 # that, if we overwrite __main__, we replace it at the end
1617 1617 main_mod_name = prog_ns['__name__']
1618 1618
1619 1619 if main_mod_name == '__main__':
1620 1620 restore_main = sys.modules['__main__']
1621 1621 else:
1622 1622 restore_main = False
1623 1623
1624 1624 # This needs to be undone at the end to prevent holding references to
1625 1625 # every single object ever created.
1626 1626 sys.modules[main_mod_name] = main_mod
1627 1627
1628 1628 stats = None
1629 1629 try:
1630 1630 self.shell.savehist()
1631 1631
1632 1632 if opts.has_key('p'):
1633 1633 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1634 1634 else:
1635 1635 if opts.has_key('d'):
1636 1636 deb = Debugger.Pdb(self.shell.rc.colors)
1637 1637 # reset Breakpoint state, which is moronically kept
1638 1638 # in a class
1639 1639 bdb.Breakpoint.next = 1
1640 1640 bdb.Breakpoint.bplist = {}
1641 1641 bdb.Breakpoint.bpbynumber = [None]
1642 1642 # Set an initial breakpoint to stop execution
1643 1643 maxtries = 10
1644 1644 bp = int(opts.get('b',[1])[0])
1645 1645 checkline = deb.checkline(filename,bp)
1646 1646 if not checkline:
1647 1647 for bp in range(bp+1,bp+maxtries+1):
1648 1648 if deb.checkline(filename,bp):
1649 1649 break
1650 1650 else:
1651 1651 msg = ("\nI failed to find a valid line to set "
1652 1652 "a breakpoint\n"
1653 1653 "after trying up to line: %s.\n"
1654 1654 "Please set a valid breakpoint manually "
1655 1655 "with the -b option." % bp)
1656 1656 error(msg)
1657 1657 return
1658 1658 # if we find a good linenumber, set the breakpoint
1659 1659 deb.do_break('%s:%s' % (filename,bp))
1660 1660 # Start file run
1661 1661 print "NOTE: Enter 'c' at the",
1662 1662 print "%s prompt to start your script." % deb.prompt
1663 1663 try:
1664 1664 deb.run('execfile("%s")' % filename,prog_ns)
1665 1665
1666 1666 except:
1667 1667 etype, value, tb = sys.exc_info()
1668 1668 # Skip three frames in the traceback: the %run one,
1669 1669 # one inside bdb.py, and the command-line typed by the
1670 1670 # user (run by exec in pdb itself).
1671 1671 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1672 1672 else:
1673 1673 if runner is None:
1674 1674 runner = self.shell.safe_execfile
1675 1675 if opts.has_key('t'):
1676 1676 # timed execution
1677 1677 try:
1678 1678 nruns = int(opts['N'][0])
1679 1679 if nruns < 1:
1680 1680 error('Number of runs must be >=1')
1681 1681 return
1682 1682 except (KeyError):
1683 1683 nruns = 1
1684 1684 if nruns == 1:
1685 1685 t0 = clock2()
1686 1686 runner(filename,prog_ns,prog_ns,
1687 1687 exit_ignore=exit_ignore)
1688 1688 t1 = clock2()
1689 1689 t_usr = t1[0]-t0[0]
1690 1690 t_sys = t1[1]-t0[1]
1691 1691 print "\nIPython CPU timings (estimated):"
1692 1692 print " User : %10s s." % t_usr
1693 1693 print " System: %10s s." % t_sys
1694 1694 else:
1695 1695 runs = range(nruns)
1696 1696 t0 = clock2()
1697 1697 for nr in runs:
1698 1698 runner(filename,prog_ns,prog_ns,
1699 1699 exit_ignore=exit_ignore)
1700 1700 t1 = clock2()
1701 1701 t_usr = t1[0]-t0[0]
1702 1702 t_sys = t1[1]-t0[1]
1703 1703 print "\nIPython CPU timings (estimated):"
1704 1704 print "Total runs performed:",nruns
1705 1705 print " Times : %10s %10s" % ('Total','Per run')
1706 1706 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1707 1707 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1708 1708
1709 1709 else:
1710 1710 # regular execution
1711 1711 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1712 1712
1713 1713 if opts.has_key('i'):
1714 1714 self.shell.user_ns['__name__'] = __name__save
1715 1715 else:
1716 1716 # The shell MUST hold a reference to prog_ns so after %run
1717 1717 # exits, the python deletion mechanism doesn't zero it out
1718 1718 # (leaving dangling references).
1719 1719 self.shell.cache_main_mod(prog_ns,filename)
1720 1720 # update IPython interactive namespace
1721 1721
1722 1722 # Some forms of read errors on the file may mean the
1723 1723 # __name__ key was never set; using pop we don't have to
1724 1724 # worry about a possible KeyError.
1725 1725 prog_ns.pop('__name__', None)
1726 1726
1727 1727 self.shell.user_ns.update(prog_ns)
1728 1728 finally:
1729 1729 # It's a bit of a mystery why, but __builtins__ can change from
1730 1730 # being a module to becoming a dict missing some key data after
1731 1731 # %run. As best I can see, this is NOT something IPython is doing
1732 1732 # at all, and similar problems have been reported before:
1733 1733 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1734 1734 # Since this seems to be done by the interpreter itself, the best
1735 1735 # we can do is to at least restore __builtins__ for the user on
1736 1736 # exit.
1737 1737 self.shell.user_ns['__builtins__'] = __builtin__
1738 1738
1739 1739 # Ensure key global structures are restored
1740 1740 sys.argv = save_argv
1741 1741 if restore_main:
1742 1742 sys.modules['__main__'] = restore_main
1743 1743 else:
1744 1744 # Remove from sys.modules the reference to main_mod we'd
1745 1745 # added. Otherwise it will trap references to objects
1746 1746 # contained therein.
1747 1747 del sys.modules[main_mod_name]
1748 1748
1749 1749 self.shell.reloadhist()
1750 1750
1751 1751 return stats
1752 1752
1753 1753 def magic_runlog(self, parameter_s =''):
1754 1754 """Run files as logs.
1755 1755
1756 1756 Usage:\\
1757 1757 %runlog file1 file2 ...
1758 1758
1759 1759 Run the named files (treating them as log files) in sequence inside
1760 1760 the interpreter, and return to the prompt. This is much slower than
1761 1761 %run because each line is executed in a try/except block, but it
1762 1762 allows running files with syntax errors in them.
1763 1763
1764 1764 Normally IPython will guess when a file is one of its own logfiles, so
1765 1765 you can typically use %run even for logs. This shorthand allows you to
1766 1766 force any file to be treated as a log file."""
1767 1767
1768 1768 for f in parameter_s.split():
1769 1769 self.shell.safe_execfile(f,self.shell.user_ns,
1770 1770 self.shell.user_ns,islog=1)
1771 1771
1772 1772 @testdec.skip_doctest
1773 1773 def magic_timeit(self, parameter_s =''):
1774 1774 """Time execution of a Python statement or expression
1775 1775
1776 1776 Usage:\\
1777 1777 %timeit [-n<N> -r<R> [-t|-c]] statement
1778 1778
1779 1779 Time execution of a Python statement or expression using the timeit
1780 1780 module.
1781 1781
1782 1782 Options:
1783 1783 -n<N>: execute the given statement <N> times in a loop. If this value
1784 1784 is not given, a fitting value is chosen.
1785 1785
1786 1786 -r<R>: repeat the loop iteration <R> times and take the best result.
1787 1787 Default: 3
1788 1788
1789 1789 -t: use time.time to measure the time, which is the default on Unix.
1790 1790 This function measures wall time.
1791 1791
1792 1792 -c: use time.clock to measure the time, which is the default on
1793 1793 Windows and measures wall time. On Unix, resource.getrusage is used
1794 1794 instead and returns the CPU user time.
1795 1795
1796 1796 -p<P>: use a precision of <P> digits to display the timing result.
1797 1797 Default: 3
1798 1798
1799 1799
1800 1800 Examples:
1801 1801
1802 1802 In [1]: %timeit pass
1803 1803 10000000 loops, best of 3: 53.3 ns per loop
1804 1804
1805 1805 In [2]: u = None
1806 1806
1807 1807 In [3]: %timeit u is None
1808 1808 10000000 loops, best of 3: 184 ns per loop
1809 1809
1810 1810 In [4]: %timeit -r 4 u == None
1811 1811 1000000 loops, best of 4: 242 ns per loop
1812 1812
1813 1813 In [5]: import time
1814 1814
1815 1815 In [6]: %timeit -n1 time.sleep(2)
1816 1816 1 loops, best of 3: 2 s per loop
1817 1817
1818 1818
1819 1819 The times reported by %timeit will be slightly higher than those
1820 1820 reported by the timeit.py script when variables are accessed. This is
1821 1821 due to the fact that %timeit executes the statement in the namespace
1822 1822 of the shell, compared with timeit.py, which uses a single setup
1823 1823 statement to import function or create variables. Generally, the bias
1824 1824 does not matter as long as results from timeit.py are not mixed with
1825 1825 those from %timeit."""
1826 1826
1827 1827 import timeit
1828 1828 import math
1829 1829
1830 1830 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1831 1831 # certain terminals. Until we figure out a robust way of
1832 1832 # auto-detecting if the terminal can deal with it, use plain 'us' for
1833 1833 # microseconds. I am really NOT happy about disabling the proper
1834 1834 # 'micro' prefix, but crashing is worse... If anyone knows what the
1835 1835 # right solution for this is, I'm all ears...
1836 1836 #
1837 1837 # Note: using
1838 1838 #
1839 1839 # s = u'\xb5'
1840 1840 # s.encode(sys.getdefaultencoding())
1841 1841 #
1842 1842 # is not sufficient, as I've seen terminals where that fails but
1843 1843 # print s
1844 1844 #
1845 1845 # succeeds
1846 1846 #
1847 1847 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1848 1848
1849 1849 #units = [u"s", u"ms",u'\xb5',"ns"]
1850 1850 units = [u"s", u"ms",u'us',"ns"]
1851 1851
1852 1852 scaling = [1, 1e3, 1e6, 1e9]
1853 1853
1854 1854 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1855 1855 posix=False)
1856 1856 if stmt == "":
1857 1857 return
1858 1858 timefunc = timeit.default_timer
1859 1859 number = int(getattr(opts, "n", 0))
1860 1860 repeat = int(getattr(opts, "r", timeit.default_repeat))
1861 1861 precision = int(getattr(opts, "p", 3))
1862 1862 if hasattr(opts, "t"):
1863 1863 timefunc = time.time
1864 1864 if hasattr(opts, "c"):
1865 1865 timefunc = clock
1866 1866
1867 1867 timer = timeit.Timer(timer=timefunc)
1868 1868 # this code has tight coupling to the inner workings of timeit.Timer,
1869 1869 # but is there a better way to achieve that the code stmt has access
1870 1870 # to the shell namespace?
1871 1871
1872 1872 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1873 1873 'setup': "pass"}
1874 1874 # Track compilation time so it can be reported if too long
1875 1875 # Minimum time above which compilation time will be reported
1876 1876 tc_min = 0.1
1877 1877
1878 1878 t0 = clock()
1879 1879 code = compile(src, "<magic-timeit>", "exec")
1880 1880 tc = clock()-t0
1881 1881
1882 1882 ns = {}
1883 1883 exec code in self.shell.user_ns, ns
1884 1884 timer.inner = ns["inner"]
1885 1885
1886 1886 if number == 0:
1887 1887 # determine number so that 0.2 <= total time < 2.0
1888 1888 number = 1
1889 1889 for i in range(1, 10):
1890 1890 if timer.timeit(number) >= 0.2:
1891 1891 break
1892 1892 number *= 10
1893 1893
1894 1894 best = min(timer.repeat(repeat, number)) / number
1895 1895
1896 1896 if best > 0.0 and best < 1000.0:
1897 1897 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1898 1898 elif best >= 1000.0:
1899 1899 order = 0
1900 1900 else:
1901 1901 order = 3
1902 1902 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1903 1903 precision,
1904 1904 best * scaling[order],
1905 1905 units[order])
1906 1906 if tc > tc_min:
1907 1907 print "Compiler time: %.2f s" % tc
1908 1908
1909 1909 @testdec.skip_doctest
1910 1910 def magic_time(self,parameter_s = ''):
1911 1911 """Time execution of a Python statement or expression.
1912 1912
1913 1913 The CPU and wall clock times are printed, and the value of the
1914 1914 expression (if any) is returned. Note that under Win32, system time
1915 1915 is always reported as 0, since it can not be measured.
1916 1916
1917 1917 This function provides very basic timing functionality. In Python
1918 1918 2.3, the timeit module offers more control and sophistication, so this
1919 1919 could be rewritten to use it (patches welcome).
1920 1920
1921 1921 Some examples:
1922 1922
1923 1923 In [1]: time 2**128
1924 1924 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1925 1925 Wall time: 0.00
1926 1926 Out[1]: 340282366920938463463374607431768211456L
1927 1927
1928 1928 In [2]: n = 1000000
1929 1929
1930 1930 In [3]: time sum(range(n))
1931 1931 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1932 1932 Wall time: 1.37
1933 1933 Out[3]: 499999500000L
1934 1934
1935 1935 In [4]: time print 'hello world'
1936 1936 hello world
1937 1937 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1938 1938 Wall time: 0.00
1939 1939
1940 1940 Note that the time needed by Python to compile the given expression
1941 1941 will be reported if it is more than 0.1s. In this example, the
1942 1942 actual exponentiation is done by Python at compilation time, so while
1943 1943 the expression can take a noticeable amount of time to compute, that
1944 1944 time is purely due to the compilation:
1945 1945
1946 1946 In [5]: time 3**9999;
1947 1947 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1948 1948 Wall time: 0.00 s
1949 1949
1950 1950 In [6]: time 3**999999;
1951 1951 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1952 1952 Wall time: 0.00 s
1953 1953 Compiler : 0.78 s
1954 1954 """
1955 1955
1956 1956 # fail immediately if the given expression can't be compiled
1957 1957
1958 1958 expr = self.shell.prefilter(parameter_s,False)
1959 1959
1960 1960 # Minimum time above which compilation time will be reported
1961 1961 tc_min = 0.1
1962 1962
1963 1963 try:
1964 1964 mode = 'eval'
1965 1965 t0 = clock()
1966 1966 code = compile(expr,'<timed eval>',mode)
1967 1967 tc = clock()-t0
1968 1968 except SyntaxError:
1969 1969 mode = 'exec'
1970 1970 t0 = clock()
1971 1971 code = compile(expr,'<timed exec>',mode)
1972 1972 tc = clock()-t0
1973 1973 # skew measurement as little as possible
1974 1974 glob = self.shell.user_ns
1975 1975 clk = clock2
1976 1976 wtime = time.time
1977 1977 # time execution
1978 1978 wall_st = wtime()
1979 1979 if mode=='eval':
1980 1980 st = clk()
1981 1981 out = eval(code,glob)
1982 1982 end = clk()
1983 1983 else:
1984 1984 st = clk()
1985 1985 exec code in glob
1986 1986 end = clk()
1987 1987 out = None
1988 1988 wall_end = wtime()
1989 1989 # Compute actual times and report
1990 1990 wall_time = wall_end-wall_st
1991 1991 cpu_user = end[0]-st[0]
1992 1992 cpu_sys = end[1]-st[1]
1993 1993 cpu_tot = cpu_user+cpu_sys
1994 1994 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1995 1995 (cpu_user,cpu_sys,cpu_tot)
1996 1996 print "Wall time: %.2f s" % wall_time
1997 1997 if tc > tc_min:
1998 1998 print "Compiler : %.2f s" % tc
1999 1999 return out
2000 2000
2001 2001 @testdec.skip_doctest
2002 2002 def magic_macro(self,parameter_s = ''):
2003 2003 """Define a set of input lines as a macro for future re-execution.
2004 2004
2005 2005 Usage:\\
2006 2006 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2007 2007
2008 2008 Options:
2009 2009
2010 2010 -r: use 'raw' input. By default, the 'processed' history is used,
2011 2011 so that magics are loaded in their transformed version to valid
2012 2012 Python. If this option is given, the raw input as typed as the
2013 2013 command line is used instead.
2014 2014
2015 2015 This will define a global variable called `name` which is a string
2016 2016 made of joining the slices and lines you specify (n1,n2,... numbers
2017 2017 above) from your input history into a single string. This variable
2018 2018 acts like an automatic function which re-executes those lines as if
2019 2019 you had typed them. You just type 'name' at the prompt and the code
2020 2020 executes.
2021 2021
2022 2022 The notation for indicating number ranges is: n1-n2 means 'use line
2023 2023 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2024 2024 using the lines numbered 5,6 and 7.
2025 2025
2026 2026 Note: as a 'hidden' feature, you can also use traditional python slice
2027 2027 notation, where N:M means numbers N through M-1.
2028 2028
2029 2029 For example, if your history contains (%hist prints it):
2030 2030
2031 2031 44: x=1
2032 2032 45: y=3
2033 2033 46: z=x+y
2034 2034 47: print x
2035 2035 48: a=5
2036 2036 49: print 'x',x,'y',y
2037 2037
2038 2038 you can create a macro with lines 44 through 47 (included) and line 49
2039 2039 called my_macro with:
2040 2040
2041 2041 In [55]: %macro my_macro 44-47 49
2042 2042
2043 2043 Now, typing `my_macro` (without quotes) will re-execute all this code
2044 2044 in one pass.
2045 2045
2046 2046 You don't need to give the line-numbers in order, and any given line
2047 2047 number can appear multiple times. You can assemble macros with any
2048 2048 lines from your input history in any order.
2049 2049
2050 2050 The macro is a simple object which holds its value in an attribute,
2051 2051 but IPython's display system checks for macros and executes them as
2052 2052 code instead of printing them when you type their name.
2053 2053
2054 2054 You can view a macro's contents by explicitly printing it with:
2055 2055
2056 2056 'print macro_name'.
2057 2057
2058 2058 For one-off cases which DON'T contain magic function calls in them you
2059 2059 can obtain similar results by explicitly executing slices from your
2060 2060 input history with:
2061 2061
2062 2062 In [60]: exec In[44:48]+In[49]"""
2063 2063
2064 2064 opts,args = self.parse_options(parameter_s,'r',mode='list')
2065 2065 if not args:
2066 2066 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2067 2067 macs.sort()
2068 2068 return macs
2069 2069 if len(args) == 1:
2070 2070 raise UsageError(
2071 2071 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2072 2072 name,ranges = args[0], args[1:]
2073 2073
2074 2074 #print 'rng',ranges # dbg
2075 2075 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2076 2076 macro = Macro(lines)
2077 2077 self.shell.user_ns.update({name:macro})
2078 2078 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2079 2079 print 'Macro contents:'
2080 2080 print macro,
2081 2081
2082 2082 def magic_save(self,parameter_s = ''):
2083 2083 """Save a set of lines to a given filename.
2084 2084
2085 2085 Usage:\\
2086 2086 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2087 2087
2088 2088 Options:
2089 2089
2090 2090 -r: use 'raw' input. By default, the 'processed' history is used,
2091 2091 so that magics are loaded in their transformed version to valid
2092 2092 Python. If this option is given, the raw input as typed as the
2093 2093 command line is used instead.
2094 2094
2095 2095 This function uses the same syntax as %macro for line extraction, but
2096 2096 instead of creating a macro it saves the resulting string to the
2097 2097 filename you specify.
2098 2098
2099 2099 It adds a '.py' extension to the file if you don't do so yourself, and
2100 2100 it asks for confirmation before overwriting existing files."""
2101 2101
2102 2102 opts,args = self.parse_options(parameter_s,'r',mode='list')
2103 2103 fname,ranges = args[0], args[1:]
2104 2104 if not fname.endswith('.py'):
2105 2105 fname += '.py'
2106 2106 if os.path.isfile(fname):
2107 2107 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2108 2108 if ans.lower() not in ['y','yes']:
2109 2109 print 'Operation cancelled.'
2110 2110 return
2111 2111 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2112 2112 f = file(fname,'w')
2113 2113 f.write(cmds)
2114 2114 f.close()
2115 2115 print 'The following commands were written to file `%s`:' % fname
2116 2116 print cmds
2117 2117
2118 2118 def _edit_macro(self,mname,macro):
2119 2119 """open an editor with the macro data in a file"""
2120 2120 filename = self.shell.mktempfile(macro.value)
2121 2121 self.shell.hooks.editor(filename)
2122 2122
2123 2123 # and make a new macro object, to replace the old one
2124 2124 mfile = open(filename)
2125 2125 mvalue = mfile.read()
2126 2126 mfile.close()
2127 2127 self.shell.user_ns[mname] = Macro(mvalue)
2128 2128
2129 2129 def magic_ed(self,parameter_s=''):
2130 2130 """Alias to %edit."""
2131 2131 return self.magic_edit(parameter_s)
2132 2132
2133 2133 @testdec.skip_doctest
2134 2134 def magic_edit(self,parameter_s='',last_call=['','']):
2135 2135 """Bring up an editor and execute the resulting code.
2136 2136
2137 2137 Usage:
2138 2138 %edit [options] [args]
2139 2139
2140 2140 %edit runs IPython's editor hook. The default version of this hook is
2141 2141 set to call the __IPYTHON__.rc.editor command. This is read from your
2142 2142 environment variable $EDITOR. If this isn't found, it will default to
2143 2143 vi under Linux/Unix and to notepad under Windows. See the end of this
2144 2144 docstring for how to change the editor hook.
2145 2145
2146 2146 You can also set the value of this editor via the command line option
2147 2147 '-editor' or in your ipythonrc file. This is useful if you wish to use
2148 2148 specifically for IPython an editor different from your typical default
2149 2149 (and for Windows users who typically don't set environment variables).
2150 2150
2151 2151 This command allows you to conveniently edit multi-line code right in
2152 2152 your IPython session.
2153 2153
2154 2154 If called without arguments, %edit opens up an empty editor with a
2155 2155 temporary file and will execute the contents of this file when you
2156 2156 close it (don't forget to save it!).
2157 2157
2158 2158
2159 2159 Options:
2160 2160
2161 2161 -n <number>: open the editor at a specified line number. By default,
2162 2162 the IPython editor hook uses the unix syntax 'editor +N filename', but
2163 2163 you can configure this by providing your own modified hook if your
2164 2164 favorite editor supports line-number specifications with a different
2165 2165 syntax.
2166 2166
2167 2167 -p: this will call the editor with the same data as the previous time
2168 2168 it was used, regardless of how long ago (in your current session) it
2169 2169 was.
2170 2170
2171 2171 -r: use 'raw' input. This option only applies to input taken from the
2172 2172 user's history. By default, the 'processed' history is used, so that
2173 2173 magics are loaded in their transformed version to valid Python. If
2174 2174 this option is given, the raw input as typed as the command line is
2175 2175 used instead. When you exit the editor, it will be executed by
2176 2176 IPython's own processor.
2177 2177
2178 2178 -x: do not execute the edited code immediately upon exit. This is
2179 2179 mainly useful if you are editing programs which need to be called with
2180 2180 command line arguments, which you can then do using %run.
2181 2181
2182 2182
2183 2183 Arguments:
2184 2184
2185 2185 If arguments are given, the following possibilites exist:
2186 2186
2187 2187 - The arguments are numbers or pairs of colon-separated numbers (like
2188 2188 1 4:8 9). These are interpreted as lines of previous input to be
2189 2189 loaded into the editor. The syntax is the same of the %macro command.
2190 2190
2191 2191 - If the argument doesn't start with a number, it is evaluated as a
2192 2192 variable and its contents loaded into the editor. You can thus edit
2193 2193 any string which contains python code (including the result of
2194 2194 previous edits).
2195 2195
2196 2196 - If the argument is the name of an object (other than a string),
2197 2197 IPython will try to locate the file where it was defined and open the
2198 2198 editor at the point where it is defined. You can use `%edit function`
2199 2199 to load an editor exactly at the point where 'function' is defined,
2200 2200 edit it and have the file be executed automatically.
2201 2201
2202 2202 If the object is a macro (see %macro for details), this opens up your
2203 2203 specified editor with a temporary file containing the macro's data.
2204 2204 Upon exit, the macro is reloaded with the contents of the file.
2205 2205
2206 2206 Note: opening at an exact line is only supported under Unix, and some
2207 2207 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2208 2208 '+NUMBER' parameter necessary for this feature. Good editors like
2209 2209 (X)Emacs, vi, jed, pico and joe all do.
2210 2210
2211 2211 - If the argument is not found as a variable, IPython will look for a
2212 2212 file with that name (adding .py if necessary) and load it into the
2213 2213 editor. It will execute its contents with execfile() when you exit,
2214 2214 loading any code in the file into your interactive namespace.
2215 2215
2216 2216 After executing your code, %edit will return as output the code you
2217 2217 typed in the editor (except when it was an existing file). This way
2218 2218 you can reload the code in further invocations of %edit as a variable,
2219 2219 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2220 2220 the output.
2221 2221
2222 2222 Note that %edit is also available through the alias %ed.
2223 2223
2224 2224 This is an example of creating a simple function inside the editor and
2225 2225 then modifying it. First, start up the editor:
2226 2226
2227 2227 In [1]: ed
2228 2228 Editing... done. Executing edited code...
2229 2229 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2230 2230
2231 2231 We can then call the function foo():
2232 2232
2233 2233 In [2]: foo()
2234 2234 foo() was defined in an editing session
2235 2235
2236 2236 Now we edit foo. IPython automatically loads the editor with the
2237 2237 (temporary) file where foo() was previously defined:
2238 2238
2239 2239 In [3]: ed foo
2240 2240 Editing... done. Executing edited code...
2241 2241
2242 2242 And if we call foo() again we get the modified version:
2243 2243
2244 2244 In [4]: foo()
2245 2245 foo() has now been changed!
2246 2246
2247 2247 Here is an example of how to edit a code snippet successive
2248 2248 times. First we call the editor:
2249 2249
2250 2250 In [5]: ed
2251 2251 Editing... done. Executing edited code...
2252 2252 hello
2253 2253 Out[5]: "print 'hello'n"
2254 2254
2255 2255 Now we call it again with the previous output (stored in _):
2256 2256
2257 2257 In [6]: ed _
2258 2258 Editing... done. Executing edited code...
2259 2259 hello world
2260 2260 Out[6]: "print 'hello world'n"
2261 2261
2262 2262 Now we call it with the output #8 (stored in _8, also as Out[8]):
2263 2263
2264 2264 In [7]: ed _8
2265 2265 Editing... done. Executing edited code...
2266 2266 hello again
2267 2267 Out[7]: "print 'hello again'n"
2268 2268
2269 2269
2270 2270 Changing the default editor hook:
2271 2271
2272 2272 If you wish to write your own editor hook, you can put it in a
2273 2273 configuration file which you load at startup time. The default hook
2274 2274 is defined in the IPython.hooks module, and you can use that as a
2275 2275 starting example for further modifications. That file also has
2276 2276 general instructions on how to set a new hook for use once you've
2277 2277 defined it."""
2278 2278
2279 2279 # FIXME: This function has become a convoluted mess. It needs a
2280 2280 # ground-up rewrite with clean, simple logic.
2281 2281
2282 2282 def make_filename(arg):
2283 2283 "Make a filename from the given args"
2284 2284 try:
2285 2285 filename = get_py_filename(arg)
2286 2286 except IOError:
2287 2287 if args.endswith('.py'):
2288 2288 filename = arg
2289 2289 else:
2290 2290 filename = None
2291 2291 return filename
2292 2292
2293 2293 # custom exceptions
2294 2294 class DataIsObject(Exception): pass
2295 2295
2296 2296 opts,args = self.parse_options(parameter_s,'prxn:')
2297 2297 # Set a few locals from the options for convenience:
2298 2298 opts_p = opts.has_key('p')
2299 2299 opts_r = opts.has_key('r')
2300 2300
2301 2301 # Default line number value
2302 2302 lineno = opts.get('n',None)
2303 2303
2304 2304 if opts_p:
2305 2305 args = '_%s' % last_call[0]
2306 2306 if not self.shell.user_ns.has_key(args):
2307 2307 args = last_call[1]
2308 2308
2309 2309 # use last_call to remember the state of the previous call, but don't
2310 2310 # let it be clobbered by successive '-p' calls.
2311 2311 try:
2312 2312 last_call[0] = self.shell.outputcache.prompt_count
2313 2313 if not opts_p:
2314 2314 last_call[1] = parameter_s
2315 2315 except:
2316 2316 pass
2317 2317
2318 2318 # by default this is done with temp files, except when the given
2319 2319 # arg is a filename
2320 2320 use_temp = 1
2321 2321
2322 2322 if re.match(r'\d',args):
2323 2323 # Mode where user specifies ranges of lines, like in %macro.
2324 2324 # This means that you can't edit files whose names begin with
2325 2325 # numbers this way. Tough.
2326 2326 ranges = args.split()
2327 2327 data = ''.join(self.extract_input_slices(ranges,opts_r))
2328 2328 elif args.endswith('.py'):
2329 2329 filename = make_filename(args)
2330 2330 data = ''
2331 2331 use_temp = 0
2332 2332 elif args:
2333 2333 try:
2334 2334 # Load the parameter given as a variable. If not a string,
2335 2335 # process it as an object instead (below)
2336 2336
2337 2337 #print '*** args',args,'type',type(args) # dbg
2338 2338 data = eval(args,self.shell.user_ns)
2339 2339 if not type(data) in StringTypes:
2340 2340 raise DataIsObject
2341 2341
2342 2342 except (NameError,SyntaxError):
2343 2343 # given argument is not a variable, try as a filename
2344 2344 filename = make_filename(args)
2345 2345 if filename is None:
2346 2346 warn("Argument given (%s) can't be found as a variable "
2347 2347 "or as a filename." % args)
2348 2348 return
2349 2349
2350 2350 data = ''
2351 2351 use_temp = 0
2352 2352 except DataIsObject:
2353 2353
2354 2354 # macros have a special edit function
2355 2355 if isinstance(data,Macro):
2356 2356 self._edit_macro(args,data)
2357 2357 return
2358 2358
2359 2359 # For objects, try to edit the file where they are defined
2360 2360 try:
2361 2361 filename = inspect.getabsfile(data)
2362 2362 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2363 2363 # class created by %edit? Try to find source
2364 2364 # by looking for method definitions instead, the
2365 2365 # __module__ in those classes is FakeModule.
2366 2366 attrs = [getattr(data, aname) for aname in dir(data)]
2367 2367 for attr in attrs:
2368 2368 if not inspect.ismethod(attr):
2369 2369 continue
2370 2370 filename = inspect.getabsfile(attr)
2371 2371 if filename and 'fakemodule' not in filename.lower():
2372 2372 # change the attribute to be the edit target instead
2373 2373 data = attr
2374 2374 break
2375 2375
2376 2376 datafile = 1
2377 2377 except TypeError:
2378 2378 filename = make_filename(args)
2379 2379 datafile = 1
2380 2380 warn('Could not find file where `%s` is defined.\n'
2381 2381 'Opening a file named `%s`' % (args,filename))
2382 2382 # Now, make sure we can actually read the source (if it was in
2383 2383 # a temp file it's gone by now).
2384 2384 if datafile:
2385 2385 try:
2386 2386 if lineno is None:
2387 2387 lineno = inspect.getsourcelines(data)[1]
2388 2388 except IOError:
2389 2389 filename = make_filename(args)
2390 2390 if filename is None:
2391 2391 warn('The file `%s` where `%s` was defined cannot '
2392 2392 'be read.' % (filename,data))
2393 2393 return
2394 2394 use_temp = 0
2395 2395 else:
2396 2396 data = ''
2397 2397
2398 2398 if use_temp:
2399 2399 filename = self.shell.mktempfile(data)
2400 2400 print 'IPython will make a temporary file named:',filename
2401 2401
2402 2402 # do actual editing here
2403 2403 print 'Editing...',
2404 2404 sys.stdout.flush()
2405 2405 try:
2406 2406 self.shell.hooks.editor(filename,lineno)
2407 2407 except IPython.ipapi.TryNext:
2408 2408 warn('Could not open editor')
2409 2409 return
2410 2410
2411 2411 # XXX TODO: should this be generalized for all string vars?
2412 2412 # For now, this is special-cased to blocks created by cpaste
2413 2413 if args.strip() == 'pasted_block':
2414 2414 self.shell.user_ns['pasted_block'] = file_read(filename)
2415 2415
2416 2416 if opts.has_key('x'): # -x prevents actual execution
2417 2417 print
2418 2418 else:
2419 2419 print 'done. Executing edited code...'
2420 2420 if opts_r:
2421 2421 self.shell.runlines(file_read(filename))
2422 2422 else:
2423 2423 self.shell.safe_execfile(filename,self.shell.user_ns,
2424 2424 self.shell.user_ns)
2425 2425
2426 2426
2427 2427 if use_temp:
2428 2428 try:
2429 2429 return open(filename).read()
2430 2430 except IOError,msg:
2431 2431 if msg.filename == filename:
2432 2432 warn('File not found. Did you forget to save?')
2433 2433 return
2434 2434 else:
2435 2435 self.shell.showtraceback()
2436 2436
2437 2437 def magic_xmode(self,parameter_s = ''):
2438 2438 """Switch modes for the exception handlers.
2439 2439
2440 2440 Valid modes: Plain, Context and Verbose.
2441 2441
2442 2442 If called without arguments, acts as a toggle."""
2443 2443
2444 2444 def xmode_switch_err(name):
2445 2445 warn('Error changing %s exception modes.\n%s' %
2446 2446 (name,sys.exc_info()[1]))
2447 2447
2448 2448 shell = self.shell
2449 2449 new_mode = parameter_s.strip().capitalize()
2450 2450 try:
2451 2451 shell.InteractiveTB.set_mode(mode=new_mode)
2452 2452 print 'Exception reporting mode:',shell.InteractiveTB.mode
2453 2453 except:
2454 2454 xmode_switch_err('user')
2455 2455
2456 2456 # threaded shells use a special handler in sys.excepthook
2457 2457 if shell.isthreaded:
2458 2458 try:
2459 2459 shell.sys_excepthook.set_mode(mode=new_mode)
2460 2460 except:
2461 2461 xmode_switch_err('threaded')
2462 2462
2463 2463 def magic_colors(self,parameter_s = ''):
2464 2464 """Switch color scheme for prompts, info system and exception handlers.
2465 2465
2466 2466 Currently implemented schemes: NoColor, Linux, LightBG.
2467 2467
2468 2468 Color scheme names are not case-sensitive."""
2469 2469
2470 2470 def color_switch_err(name):
2471 2471 warn('Error changing %s color schemes.\n%s' %
2472 2472 (name,sys.exc_info()[1]))
2473 2473
2474 2474
2475 2475 new_scheme = parameter_s.strip()
2476 2476 if not new_scheme:
2477 2477 raise UsageError(
2478 2478 "%colors: you must specify a color scheme. See '%colors?'")
2479 2479 return
2480 2480 # local shortcut
2481 2481 shell = self.shell
2482 2482
2483 2483 import IPython.rlineimpl as readline
2484 2484
2485 2485 if not readline.have_readline and sys.platform == "win32":
2486 2486 msg = """\
2487 2487 Proper color support under MS Windows requires the pyreadline library.
2488 2488 You can find it at:
2489 2489 http://ipython.scipy.org/moin/PyReadline/Intro
2490 2490 Gary's readline needs the ctypes module, from:
2491 2491 http://starship.python.net/crew/theller/ctypes
2492 2492 (Note that ctypes is already part of Python versions 2.5 and newer).
2493 2493
2494 2494 Defaulting color scheme to 'NoColor'"""
2495 2495 new_scheme = 'NoColor'
2496 2496 warn(msg)
2497 2497
2498 2498 # readline option is 0
2499 2499 if not shell.has_readline:
2500 2500 new_scheme = 'NoColor'
2501 2501
2502 2502 # Set prompt colors
2503 2503 try:
2504 2504 shell.outputcache.set_colors(new_scheme)
2505 2505 except:
2506 2506 color_switch_err('prompt')
2507 2507 else:
2508 2508 shell.rc.colors = \
2509 2509 shell.outputcache.color_table.active_scheme_name
2510 2510 # Set exception colors
2511 2511 try:
2512 2512 shell.InteractiveTB.set_colors(scheme = new_scheme)
2513 2513 shell.SyntaxTB.set_colors(scheme = new_scheme)
2514 2514 except:
2515 2515 color_switch_err('exception')
2516 2516
2517 2517 # threaded shells use a verbose traceback in sys.excepthook
2518 2518 if shell.isthreaded:
2519 2519 try:
2520 2520 shell.sys_excepthook.set_colors(scheme=new_scheme)
2521 2521 except:
2522 2522 color_switch_err('system exception handler')
2523 2523
2524 2524 # Set info (for 'object?') colors
2525 2525 if shell.rc.color_info:
2526 2526 try:
2527 2527 shell.inspector.set_active_scheme(new_scheme)
2528 2528 except:
2529 2529 color_switch_err('object inspector')
2530 2530 else:
2531 2531 shell.inspector.set_active_scheme('NoColor')
2532 2532
2533 2533 def magic_color_info(self,parameter_s = ''):
2534 2534 """Toggle color_info.
2535 2535
2536 2536 The color_info configuration parameter controls whether colors are
2537 2537 used for displaying object details (by things like %psource, %pfile or
2538 2538 the '?' system). This function toggles this value with each call.
2539 2539
2540 2540 Note that unless you have a fairly recent pager (less works better
2541 2541 than more) in your system, using colored object information displays
2542 2542 will not work properly. Test it and see."""
2543 2543
2544 2544 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2545 2545 self.magic_colors(self.shell.rc.colors)
2546 2546 print 'Object introspection functions have now coloring:',
2547 2547 print ['OFF','ON'][self.shell.rc.color_info]
2548 2548
2549 2549 def magic_Pprint(self, parameter_s=''):
2550 2550 """Toggle pretty printing on/off."""
2551 2551
2552 2552 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2553 2553 print 'Pretty printing has been turned', \
2554 2554 ['OFF','ON'][self.shell.rc.pprint]
2555 2555
2556 2556 def magic_exit(self, parameter_s=''):
2557 2557 """Exit IPython, confirming if configured to do so.
2558 2558
2559 2559 You can configure whether IPython asks for confirmation upon exit by
2560 2560 setting the confirm_exit flag in the ipythonrc file."""
2561 2561
2562 2562 self.shell.exit()
2563 2563
2564 2564 def magic_quit(self, parameter_s=''):
2565 2565 """Exit IPython, confirming if configured to do so (like %exit)"""
2566 2566
2567 2567 self.shell.exit()
2568 2568
2569 2569 def magic_Exit(self, parameter_s=''):
2570 2570 """Exit IPython without confirmation."""
2571 2571
2572 2572 self.shell.ask_exit()
2573 2573
2574 2574 #......................................................................
2575 2575 # Functions to implement unix shell-type things
2576 2576
2577 2577 @testdec.skip_doctest
2578 2578 def magic_alias(self, parameter_s = ''):
2579 2579 """Define an alias for a system command.
2580 2580
2581 2581 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2582 2582
2583 2583 Then, typing 'alias_name params' will execute the system command 'cmd
2584 2584 params' (from your underlying operating system).
2585 2585
2586 2586 Aliases have lower precedence than magic functions and Python normal
2587 2587 variables, so if 'foo' is both a Python variable and an alias, the
2588 2588 alias can not be executed until 'del foo' removes the Python variable.
2589 2589
2590 2590 You can use the %l specifier in an alias definition to represent the
2591 2591 whole line when the alias is called. For example:
2592 2592
2593 2593 In [2]: alias all echo "Input in brackets: <%l>"
2594 2594 In [3]: all hello world
2595 2595 Input in brackets: <hello world>
2596 2596
2597 2597 You can also define aliases with parameters using %s specifiers (one
2598 2598 per parameter):
2599 2599
2600 2600 In [1]: alias parts echo first %s second %s
2601 2601 In [2]: %parts A B
2602 2602 first A second B
2603 2603 In [3]: %parts A
2604 2604 Incorrect number of arguments: 2 expected.
2605 2605 parts is an alias to: 'echo first %s second %s'
2606 2606
2607 2607 Note that %l and %s are mutually exclusive. You can only use one or
2608 2608 the other in your aliases.
2609 2609
2610 2610 Aliases expand Python variables just like system calls using ! or !!
2611 2611 do: all expressions prefixed with '$' get expanded. For details of
2612 2612 the semantic rules, see PEP-215:
2613 2613 http://www.python.org/peps/pep-0215.html. This is the library used by
2614 2614 IPython for variable expansion. If you want to access a true shell
2615 2615 variable, an extra $ is necessary to prevent its expansion by IPython:
2616 2616
2617 2617 In [6]: alias show echo
2618 2618 In [7]: PATH='A Python string'
2619 2619 In [8]: show $PATH
2620 2620 A Python string
2621 2621 In [9]: show $$PATH
2622 2622 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2623 2623
2624 2624 You can use the alias facility to acess all of $PATH. See the %rehash
2625 2625 and %rehashx functions, which automatically create aliases for the
2626 2626 contents of your $PATH.
2627 2627
2628 2628 If called with no parameters, %alias prints the current alias table."""
2629 2629
2630 2630 par = parameter_s.strip()
2631 2631 if not par:
2632 2632 stored = self.db.get('stored_aliases', {} )
2633 2633 atab = self.shell.alias_table
2634 2634 aliases = atab.keys()
2635 2635 aliases.sort()
2636 2636 res = []
2637 2637 showlast = []
2638 2638 for alias in aliases:
2639 2639 special = False
2640 2640 try:
2641 2641 tgt = atab[alias][1]
2642 2642 except (TypeError, AttributeError):
2643 2643 # unsubscriptable? probably a callable
2644 2644 tgt = atab[alias]
2645 2645 special = True
2646 2646 # 'interesting' aliases
2647 2647 if (alias in stored or
2648 2648 special or
2649 2649 alias.lower() != os.path.splitext(tgt)[0].lower() or
2650 2650 ' ' in tgt):
2651 2651 showlast.append((alias, tgt))
2652 2652 else:
2653 2653 res.append((alias, tgt ))
2654 2654
2655 2655 # show most interesting aliases last
2656 2656 res.extend(showlast)
2657 2657 print "Total number of aliases:",len(aliases)
2658 2658 return res
2659 2659 try:
2660 2660 alias,cmd = par.split(None,1)
2661 2661 except:
2662 2662 print OInspect.getdoc(self.magic_alias)
2663 2663 else:
2664 2664 nargs = cmd.count('%s')
2665 2665 if nargs>0 and cmd.find('%l')>=0:
2666 2666 error('The %s and %l specifiers are mutually exclusive '
2667 2667 'in alias definitions.')
2668 2668 else: # all looks OK
2669 2669 self.shell.alias_table[alias] = (nargs,cmd)
2670 2670 self.shell.alias_table_validate(verbose=0)
2671 2671 # end magic_alias
2672 2672
2673 2673 def magic_unalias(self, parameter_s = ''):
2674 2674 """Remove an alias"""
2675 2675
2676 2676 aname = parameter_s.strip()
2677 2677 if aname in self.shell.alias_table:
2678 2678 del self.shell.alias_table[aname]
2679 2679 stored = self.db.get('stored_aliases', {} )
2680 2680 if aname in stored:
2681 2681 print "Removing %stored alias",aname
2682 2682 del stored[aname]
2683 2683 self.db['stored_aliases'] = stored
2684 2684
2685 2685
2686 2686 def magic_rehashx(self, parameter_s = ''):
2687 2687 """Update the alias table with all executable files in $PATH.
2688 2688
2689 2689 This version explicitly checks that every entry in $PATH is a file
2690 2690 with execute access (os.X_OK), so it is much slower than %rehash.
2691 2691
2692 2692 Under Windows, it checks executability as a match agains a
2693 2693 '|'-separated string of extensions, stored in the IPython config
2694 2694 variable win_exec_ext. This defaults to 'exe|com|bat'.
2695 2695
2696 2696 This function also resets the root module cache of module completer,
2697 2697 used on slow filesystems.
2698 2698 """
2699 2699
2700 2700
2701 2701 ip = self.api
2702 2702
2703 2703 # for the benefit of module completer in ipy_completers.py
2704 2704 del ip.db['rootmodules']
2705 2705
2706 2706 path = [os.path.abspath(os.path.expanduser(p)) for p in
2707 2707 os.environ.get('PATH','').split(os.pathsep)]
2708 2708 path = filter(os.path.isdir,path)
2709 2709
2710 2710 alias_table = self.shell.alias_table
2711 2711 syscmdlist = []
2712 2712 if os.name == 'posix':
2713 2713 isexec = lambda fname:os.path.isfile(fname) and \
2714 2714 os.access(fname,os.X_OK)
2715 2715 else:
2716 2716
2717 2717 try:
2718 2718 winext = os.environ['pathext'].replace(';','|').replace('.','')
2719 2719 except KeyError:
2720 2720 winext = 'exe|com|bat|py'
2721 2721 if 'py' not in winext:
2722 2722 winext += '|py'
2723 2723 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2724 2724 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2725 2725 savedir = os.getcwd()
2726 2726 try:
2727 2727 # write the whole loop for posix/Windows so we don't have an if in
2728 2728 # the innermost part
2729 2729 if os.name == 'posix':
2730 2730 for pdir in path:
2731 2731 os.chdir(pdir)
2732 2732 for ff in os.listdir(pdir):
2733 2733 if isexec(ff) and ff not in self.shell.no_alias:
2734 2734 # each entry in the alias table must be (N,name),
2735 2735 # where N is the number of positional arguments of the
2736 2736 # alias.
2737 2737 # Dots will be removed from alias names, since ipython
2738 2738 # assumes names with dots to be python code
2739 2739 alias_table[ff.replace('.','')] = (0,ff)
2740 2740 syscmdlist.append(ff)
2741 2741 else:
2742 2742 for pdir in path:
2743 2743 os.chdir(pdir)
2744 2744 for ff in os.listdir(pdir):
2745 2745 base, ext = os.path.splitext(ff)
2746 2746 if isexec(ff) and base.lower() not in self.shell.no_alias:
2747 2747 if ext.lower() == '.exe':
2748 2748 ff = base
2749 2749 alias_table[base.lower().replace('.','')] = (0,ff)
2750 2750 syscmdlist.append(ff)
2751 2751 # Make sure the alias table doesn't contain keywords or builtins
2752 2752 self.shell.alias_table_validate()
2753 2753 # Call again init_auto_alias() so we get 'rm -i' and other
2754 2754 # modified aliases since %rehashx will probably clobber them
2755 2755
2756 2756 # no, we don't want them. if %rehashx clobbers them, good,
2757 2757 # we'll probably get better versions
2758 2758 # self.shell.init_auto_alias()
2759 2759 db = ip.db
2760 2760 db['syscmdlist'] = syscmdlist
2761 2761 finally:
2762 2762 os.chdir(savedir)
2763 2763
2764 2764 def magic_pwd(self, parameter_s = ''):
2765 2765 """Return the current working directory path."""
2766 2766 return os.getcwd()
2767 2767
2768 2768 def magic_cd(self, parameter_s=''):
2769 2769 """Change the current working directory.
2770 2770
2771 2771 This command automatically maintains an internal list of directories
2772 2772 you visit during your IPython session, in the variable _dh. The
2773 2773 command %dhist shows this history nicely formatted. You can also
2774 2774 do 'cd -<tab>' to see directory history conveniently.
2775 2775
2776 2776 Usage:
2777 2777
2778 2778 cd 'dir': changes to directory 'dir'.
2779 2779
2780 2780 cd -: changes to the last visited directory.
2781 2781
2782 2782 cd -<n>: changes to the n-th directory in the directory history.
2783 2783
2784 2784 cd --foo: change to directory that matches 'foo' in history
2785 2785
2786 2786 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2787 2787 (note: cd <bookmark_name> is enough if there is no
2788 2788 directory <bookmark_name>, but a bookmark with the name exists.)
2789 2789 'cd -b <tab>' allows you to tab-complete bookmark names.
2790 2790
2791 2791 Options:
2792 2792
2793 2793 -q: quiet. Do not print the working directory after the cd command is
2794 2794 executed. By default IPython's cd command does print this directory,
2795 2795 since the default prompts do not display path information.
2796 2796
2797 2797 Note that !cd doesn't work for this purpose because the shell where
2798 2798 !command runs is immediately discarded after executing 'command'."""
2799 2799
2800 2800 parameter_s = parameter_s.strip()
2801 2801 #bkms = self.shell.persist.get("bookmarks",{})
2802 2802
2803 2803 oldcwd = os.getcwd()
2804 2804 numcd = re.match(r'(-)(\d+)$',parameter_s)
2805 2805 # jump in directory history by number
2806 2806 if numcd:
2807 2807 nn = int(numcd.group(2))
2808 2808 try:
2809 2809 ps = self.shell.user_ns['_dh'][nn]
2810 2810 except IndexError:
2811 2811 print 'The requested directory does not exist in history.'
2812 2812 return
2813 2813 else:
2814 2814 opts = {}
2815 2815 elif parameter_s.startswith('--'):
2816 2816 ps = None
2817 2817 fallback = None
2818 2818 pat = parameter_s[2:]
2819 2819 dh = self.shell.user_ns['_dh']
2820 2820 # first search only by basename (last component)
2821 2821 for ent in reversed(dh):
2822 2822 if pat in os.path.basename(ent) and os.path.isdir(ent):
2823 2823 ps = ent
2824 2824 break
2825 2825
2826 2826 if fallback is None and pat in ent and os.path.isdir(ent):
2827 2827 fallback = ent
2828 2828
2829 2829 # if we have no last part match, pick the first full path match
2830 2830 if ps is None:
2831 2831 ps = fallback
2832 2832
2833 2833 if ps is None:
2834 2834 print "No matching entry in directory history"
2835 2835 return
2836 2836 else:
2837 2837 opts = {}
2838 2838
2839 2839
2840 2840 else:
2841 2841 #turn all non-space-escaping backslashes to slashes,
2842 2842 # for c:\windows\directory\names\
2843 2843 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2844 2844 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2845 2845 # jump to previous
2846 2846 if ps == '-':
2847 2847 try:
2848 2848 ps = self.shell.user_ns['_dh'][-2]
2849 2849 except IndexError:
2850 2850 raise UsageError('%cd -: No previous directory to change to.')
2851 2851 # jump to bookmark if needed
2852 2852 else:
2853 2853 if not os.path.isdir(ps) or opts.has_key('b'):
2854 2854 bkms = self.db.get('bookmarks', {})
2855 2855
2856 2856 if bkms.has_key(ps):
2857 2857 target = bkms[ps]
2858 2858 print '(bookmark:%s) -> %s' % (ps,target)
2859 2859 ps = target
2860 2860 else:
2861 2861 if opts.has_key('b'):
2862 2862 raise UsageError("Bookmark '%s' not found. "
2863 2863 "Use '%%bookmark -l' to see your bookmarks." % ps)
2864 2864
2865 2865 # at this point ps should point to the target dir
2866 2866 if ps:
2867 2867 try:
2868 2868 os.chdir(os.path.expanduser(ps))
2869 2869 if self.shell.rc.term_title:
2870 2870 #print 'set term title:',self.shell.rc.term_title # dbg
2871 2871 platutils.set_term_title('IPy ' + abbrev_cwd())
2872 2872 except OSError:
2873 2873 print sys.exc_info()[1]
2874 2874 else:
2875 2875 cwd = os.getcwd()
2876 2876 dhist = self.shell.user_ns['_dh']
2877 2877 if oldcwd != cwd:
2878 2878 dhist.append(cwd)
2879 2879 self.db['dhist'] = compress_dhist(dhist)[-100:]
2880 2880
2881 2881 else:
2882 2882 os.chdir(self.shell.home_dir)
2883 2883 if self.shell.rc.term_title:
2884 2884 platutils.set_term_title("IPy ~")
2885 2885 cwd = os.getcwd()
2886 2886 dhist = self.shell.user_ns['_dh']
2887 2887
2888 2888 if oldcwd != cwd:
2889 2889 dhist.append(cwd)
2890 2890 self.db['dhist'] = compress_dhist(dhist)[-100:]
2891 2891 if not 'q' in opts and self.shell.user_ns['_dh']:
2892 2892 print self.shell.user_ns['_dh'][-1]
2893 2893
2894 2894
2895 2895 def magic_env(self, parameter_s=''):
2896 2896 """List environment variables."""
2897 2897
2898 2898 return os.environ.data
2899 2899
2900 2900 def magic_pushd(self, parameter_s=''):
2901 2901 """Place the current dir on stack and change directory.
2902 2902
2903 2903 Usage:\\
2904 2904 %pushd ['dirname']
2905 2905 """
2906 2906
2907 2907 dir_s = self.shell.dir_stack
2908 2908 tgt = os.path.expanduser(parameter_s)
2909 2909 cwd = os.getcwd().replace(self.home_dir,'~')
2910 2910 if tgt:
2911 2911 self.magic_cd(parameter_s)
2912 2912 dir_s.insert(0,cwd)
2913 2913 return self.magic_dirs()
2914 2914
2915 2915 def magic_popd(self, parameter_s=''):
2916 2916 """Change to directory popped off the top of the stack.
2917 2917 """
2918 2918 if not self.shell.dir_stack:
2919 2919 raise UsageError("%popd on empty stack")
2920 2920 top = self.shell.dir_stack.pop(0)
2921 2921 self.magic_cd(top)
2922 2922 print "popd ->",top
2923 2923
2924 2924 def magic_dirs(self, parameter_s=''):
2925 2925 """Return the current directory stack."""
2926 2926
2927 2927 return self.shell.dir_stack
2928 2928
2929 2929 def magic_dhist(self, parameter_s=''):
2930 2930 """Print your history of visited directories.
2931 2931
2932 2932 %dhist -> print full history\\
2933 2933 %dhist n -> print last n entries only\\
2934 2934 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2935 2935
2936 2936 This history is automatically maintained by the %cd command, and
2937 2937 always available as the global list variable _dh. You can use %cd -<n>
2938 2938 to go to directory number <n>.
2939 2939
2940 2940 Note that most of time, you should view directory history by entering
2941 2941 cd -<TAB>.
2942 2942
2943 2943 """
2944 2944
2945 2945 dh = self.shell.user_ns['_dh']
2946 2946 if parameter_s:
2947 2947 try:
2948 2948 args = map(int,parameter_s.split())
2949 2949 except:
2950 2950 self.arg_err(Magic.magic_dhist)
2951 2951 return
2952 2952 if len(args) == 1:
2953 2953 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2954 2954 elif len(args) == 2:
2955 2955 ini,fin = args
2956 2956 else:
2957 2957 self.arg_err(Magic.magic_dhist)
2958 2958 return
2959 2959 else:
2960 2960 ini,fin = 0,len(dh)
2961 2961 nlprint(dh,
2962 2962 header = 'Directory history (kept in _dh)',
2963 2963 start=ini,stop=fin)
2964 2964
2965 2965 @testdec.skip_doctest
2966 2966 def magic_sc(self, parameter_s=''):
2967 2967 """Shell capture - execute a shell command and capture its output.
2968 2968
2969 2969 DEPRECATED. Suboptimal, retained for backwards compatibility.
2970 2970
2971 2971 You should use the form 'var = !command' instead. Example:
2972 2972
2973 2973 "%sc -l myfiles = ls ~" should now be written as
2974 2974
2975 2975 "myfiles = !ls ~"
2976 2976
2977 2977 myfiles.s, myfiles.l and myfiles.n still apply as documented
2978 2978 below.
2979 2979
2980 2980 --
2981 2981 %sc [options] varname=command
2982 2982
2983 2983 IPython will run the given command using commands.getoutput(), and
2984 2984 will then update the user's interactive namespace with a variable
2985 2985 called varname, containing the value of the call. Your command can
2986 2986 contain shell wildcards, pipes, etc.
2987 2987
2988 2988 The '=' sign in the syntax is mandatory, and the variable name you
2989 2989 supply must follow Python's standard conventions for valid names.
2990 2990
2991 2991 (A special format without variable name exists for internal use)
2992 2992
2993 2993 Options:
2994 2994
2995 2995 -l: list output. Split the output on newlines into a list before
2996 2996 assigning it to the given variable. By default the output is stored
2997 2997 as a single string.
2998 2998
2999 2999 -v: verbose. Print the contents of the variable.
3000 3000
3001 3001 In most cases you should not need to split as a list, because the
3002 3002 returned value is a special type of string which can automatically
3003 3003 provide its contents either as a list (split on newlines) or as a
3004 3004 space-separated string. These are convenient, respectively, either
3005 3005 for sequential processing or to be passed to a shell command.
3006 3006
3007 3007 For example:
3008 3008
3009 3009 # all-random
3010 3010
3011 3011 # Capture into variable a
3012 3012 In [1]: sc a=ls *py
3013 3013
3014 3014 # a is a string with embedded newlines
3015 3015 In [2]: a
3016 3016 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3017 3017
3018 3018 # which can be seen as a list:
3019 3019 In [3]: a.l
3020 3020 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3021 3021
3022 3022 # or as a whitespace-separated string:
3023 3023 In [4]: a.s
3024 3024 Out[4]: 'setup.py win32_manual_post_install.py'
3025 3025
3026 3026 # a.s is useful to pass as a single command line:
3027 3027 In [5]: !wc -l $a.s
3028 3028 146 setup.py
3029 3029 130 win32_manual_post_install.py
3030 3030 276 total
3031 3031
3032 3032 # while the list form is useful to loop over:
3033 3033 In [6]: for f in a.l:
3034 3034 ...: !wc -l $f
3035 3035 ...:
3036 3036 146 setup.py
3037 3037 130 win32_manual_post_install.py
3038 3038
3039 3039 Similiarly, the lists returned by the -l option are also special, in
3040 3040 the sense that you can equally invoke the .s attribute on them to
3041 3041 automatically get a whitespace-separated string from their contents:
3042 3042
3043 3043 In [7]: sc -l b=ls *py
3044 3044
3045 3045 In [8]: b
3046 3046 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3047 3047
3048 3048 In [9]: b.s
3049 3049 Out[9]: 'setup.py win32_manual_post_install.py'
3050 3050
3051 3051 In summary, both the lists and strings used for ouptut capture have
3052 3052 the following special attributes:
3053 3053
3054 3054 .l (or .list) : value as list.
3055 3055 .n (or .nlstr): value as newline-separated string.
3056 3056 .s (or .spstr): value as space-separated string.
3057 3057 """
3058 3058
3059 3059 opts,args = self.parse_options(parameter_s,'lv')
3060 3060 # Try to get a variable name and command to run
3061 3061 try:
3062 3062 # the variable name must be obtained from the parse_options
3063 3063 # output, which uses shlex.split to strip options out.
3064 3064 var,_ = args.split('=',1)
3065 3065 var = var.strip()
3066 3066 # But the the command has to be extracted from the original input
3067 3067 # parameter_s, not on what parse_options returns, to avoid the
3068 3068 # quote stripping which shlex.split performs on it.
3069 3069 _,cmd = parameter_s.split('=',1)
3070 3070 except ValueError:
3071 3071 var,cmd = '',''
3072 3072 # If all looks ok, proceed
3073 3073 out,err = self.shell.getoutputerror(cmd)
3074 3074 if err:
3075 3075 print >> Term.cerr,err
3076 3076 if opts.has_key('l'):
3077 3077 out = SList(out.split('\n'))
3078 3078 else:
3079 3079 out = LSString(out)
3080 3080 if opts.has_key('v'):
3081 3081 print '%s ==\n%s' % (var,pformat(out))
3082 3082 if var:
3083 3083 self.shell.user_ns.update({var:out})
3084 3084 else:
3085 3085 return out
3086 3086
3087 3087 def magic_sx(self, parameter_s=''):
3088 3088 """Shell execute - run a shell command and capture its output.
3089 3089
3090 3090 %sx command
3091 3091
3092 3092 IPython will run the given command using commands.getoutput(), and
3093 3093 return the result formatted as a list (split on '\\n'). Since the
3094 3094 output is _returned_, it will be stored in ipython's regular output
3095 3095 cache Out[N] and in the '_N' automatic variables.
3096 3096
3097 3097 Notes:
3098 3098
3099 3099 1) If an input line begins with '!!', then %sx is automatically
3100 3100 invoked. That is, while:
3101 3101 !ls
3102 3102 causes ipython to simply issue system('ls'), typing
3103 3103 !!ls
3104 3104 is a shorthand equivalent to:
3105 3105 %sx ls
3106 3106
3107 3107 2) %sx differs from %sc in that %sx automatically splits into a list,
3108 3108 like '%sc -l'. The reason for this is to make it as easy as possible
3109 3109 to process line-oriented shell output via further python commands.
3110 3110 %sc is meant to provide much finer control, but requires more
3111 3111 typing.
3112 3112
3113 3113 3) Just like %sc -l, this is a list with special attributes:
3114 3114
3115 3115 .l (or .list) : value as list.
3116 3116 .n (or .nlstr): value as newline-separated string.
3117 3117 .s (or .spstr): value as whitespace-separated string.
3118 3118
3119 3119 This is very useful when trying to use such lists as arguments to
3120 3120 system commands."""
3121 3121
3122 3122 if parameter_s:
3123 3123 out,err = self.shell.getoutputerror(parameter_s)
3124 3124 if err:
3125 3125 print >> Term.cerr,err
3126 3126 return SList(out.split('\n'))
3127 3127
3128 3128 def magic_bg(self, parameter_s=''):
3129 3129 """Run a job in the background, in a separate thread.
3130 3130
3131 3131 For example,
3132 3132
3133 3133 %bg myfunc(x,y,z=1)
3134 3134
3135 3135 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3136 3136 execution starts, a message will be printed indicating the job
3137 3137 number. If your job number is 5, you can use
3138 3138
3139 3139 myvar = jobs.result(5) or myvar = jobs[5].result
3140 3140
3141 3141 to assign this result to variable 'myvar'.
3142 3142
3143 3143 IPython has a job manager, accessible via the 'jobs' object. You can
3144 3144 type jobs? to get more information about it, and use jobs.<TAB> to see
3145 3145 its attributes. All attributes not starting with an underscore are
3146 3146 meant for public use.
3147 3147
3148 3148 In particular, look at the jobs.new() method, which is used to create
3149 3149 new jobs. This magic %bg function is just a convenience wrapper
3150 3150 around jobs.new(), for expression-based jobs. If you want to create a
3151 3151 new job with an explicit function object and arguments, you must call
3152 3152 jobs.new() directly.
3153 3153
3154 3154 The jobs.new docstring also describes in detail several important
3155 3155 caveats associated with a thread-based model for background job
3156 3156 execution. Type jobs.new? for details.
3157 3157
3158 3158 You can check the status of all jobs with jobs.status().
3159 3159
3160 3160 The jobs variable is set by IPython into the Python builtin namespace.
3161 3161 If you ever declare a variable named 'jobs', you will shadow this
3162 3162 name. You can either delete your global jobs variable to regain
3163 3163 access to the job manager, or make a new name and assign it manually
3164 3164 to the manager (stored in IPython's namespace). For example, to
3165 3165 assign the job manager to the Jobs name, use:
3166 3166
3167 3167 Jobs = __builtins__.jobs"""
3168 3168
3169 3169 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3170 3170
3171 3171 def magic_r(self, parameter_s=''):
3172 3172 """Repeat previous input.
3173 3173
3174 3174 Note: Consider using the more powerfull %rep instead!
3175 3175
3176 3176 If given an argument, repeats the previous command which starts with
3177 3177 the same string, otherwise it just repeats the previous input.
3178 3178
3179 3179 Shell escaped commands (with ! as first character) are not recognized
3180 3180 by this system, only pure python code and magic commands.
3181 3181 """
3182 3182
3183 3183 start = parameter_s.strip()
3184 3184 esc_magic = self.shell.ESC_MAGIC
3185 3185 # Identify magic commands even if automagic is on (which means
3186 3186 # the in-memory version is different from that typed by the user).
3187 3187 if self.shell.rc.automagic:
3188 3188 start_magic = esc_magic+start
3189 3189 else:
3190 3190 start_magic = start
3191 3191 # Look through the input history in reverse
3192 3192 for n in range(len(self.shell.input_hist)-2,0,-1):
3193 3193 input = self.shell.input_hist[n]
3194 3194 # skip plain 'r' lines so we don't recurse to infinity
3195 3195 if input != '_ip.magic("r")\n' and \
3196 3196 (input.startswith(start) or input.startswith(start_magic)):
3197 3197 #print 'match',`input` # dbg
3198 3198 print 'Executing:',input,
3199 3199 self.shell.runlines(input)
3200 3200 return
3201 3201 print 'No previous input matching `%s` found.' % start
3202 3202
3203 3203
3204 3204 def magic_bookmark(self, parameter_s=''):
3205 3205 """Manage IPython's bookmark system.
3206 3206
3207 3207 %bookmark <name> - set bookmark to current dir
3208 3208 %bookmark <name> <dir> - set bookmark to <dir>
3209 3209 %bookmark -l - list all bookmarks
3210 3210 %bookmark -d <name> - remove bookmark
3211 3211 %bookmark -r - remove all bookmarks
3212 3212
3213 3213 You can later on access a bookmarked folder with:
3214 3214 %cd -b <name>
3215 3215 or simply '%cd <name>' if there is no directory called <name> AND
3216 3216 there is such a bookmark defined.
3217 3217
3218 3218 Your bookmarks persist through IPython sessions, but they are
3219 3219 associated with each profile."""
3220 3220
3221 3221 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3222 3222 if len(args) > 2:
3223 3223 raise UsageError("%bookmark: too many arguments")
3224 3224
3225 3225 bkms = self.db.get('bookmarks',{})
3226 3226
3227 3227 if opts.has_key('d'):
3228 3228 try:
3229 3229 todel = args[0]
3230 3230 except IndexError:
3231 3231 raise UsageError(
3232 3232 "%bookmark -d: must provide a bookmark to delete")
3233 3233 else:
3234 3234 try:
3235 3235 del bkms[todel]
3236 3236 except KeyError:
3237 3237 raise UsageError(
3238 3238 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3239 3239
3240 3240 elif opts.has_key('r'):
3241 3241 bkms = {}
3242 3242 elif opts.has_key('l'):
3243 3243 bks = bkms.keys()
3244 3244 bks.sort()
3245 3245 if bks:
3246 3246 size = max(map(len,bks))
3247 3247 else:
3248 3248 size = 0
3249 3249 fmt = '%-'+str(size)+'s -> %s'
3250 3250 print 'Current bookmarks:'
3251 3251 for bk in bks:
3252 3252 print fmt % (bk,bkms[bk])
3253 3253 else:
3254 3254 if not args:
3255 3255 raise UsageError("%bookmark: You must specify the bookmark name")
3256 3256 elif len(args)==1:
3257 3257 bkms[args[0]] = os.getcwd()
3258 3258 elif len(args)==2:
3259 3259 bkms[args[0]] = args[1]
3260 3260 self.db['bookmarks'] = bkms
3261 3261
3262 3262 def magic_pycat(self, parameter_s=''):
3263 3263 """Show a syntax-highlighted file through a pager.
3264 3264
3265 3265 This magic is similar to the cat utility, but it will assume the file
3266 3266 to be Python source and will show it with syntax highlighting. """
3267 3267
3268 3268 try:
3269 3269 filename = get_py_filename(parameter_s)
3270 3270 cont = file_read(filename)
3271 3271 except IOError:
3272 3272 try:
3273 3273 cont = eval(parameter_s,self.user_ns)
3274 3274 except NameError:
3275 3275 cont = None
3276 3276 if cont is None:
3277 3277 print "Error: no such file or variable"
3278 3278 return
3279 3279
3280 3280 page(self.shell.pycolorize(cont),
3281 3281 screen_lines=self.shell.rc.screen_length)
3282 3282
3283 3283 def _rerun_pasted(self):
3284 3284 """ Rerun a previously pasted command.
3285 3285 """
3286 3286 b = self.user_ns.get('pasted_block', None)
3287 3287 if b is None:
3288 3288 raise UsageError('No previous pasted block available')
3289 3289 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3290 3290 exec b in self.user_ns
3291 3291
3292 3292 def _get_pasted_lines(self, sentinel):
3293 3293 """ Yield pasted lines until the user enters the given sentinel value.
3294 3294 """
3295 3295 from IPython import iplib
3296 3296 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3297 3297 while True:
3298 3298 l = iplib.raw_input_original(':')
3299 3299 if l == sentinel:
3300 3300 return
3301 3301 else:
3302 3302 yield l
3303 3303
3304 3304 def _strip_pasted_lines_for_code(self, raw_lines):
3305 3305 """ Strip non-code parts of a sequence of lines to return a block of
3306 3306 code.
3307 3307 """
3308 3308 # Regular expressions that declare text we strip from the input:
3309 3309 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3310 3310 r'^\s*(\s?>)+', # Python input prompt
3311 3311 r'^\s*\.{3,}', # Continuation prompts
3312 3312 r'^\++',
3313 3313 ]
3314 3314
3315 3315 strip_from_start = map(re.compile,strip_re)
3316 3316
3317 3317 lines = []
3318 3318 for l in raw_lines:
3319 3319 for pat in strip_from_start:
3320 3320 l = pat.sub('',l)
3321 3321 lines.append(l)
3322 3322
3323 3323 block = "\n".join(lines) + '\n'
3324 3324 #print "block:\n",block
3325 3325 return block
3326 3326
3327 3327 def _execute_block(self, block, par):
3328 3328 """ Execute a block, or store it in a variable, per the user's request.
3329 3329 """
3330 3330 if not par:
3331 3331 b = textwrap.dedent(block)
3332 3332 self.user_ns['pasted_block'] = b
3333 3333 exec b in self.user_ns
3334 3334 else:
3335 3335 self.user_ns[par] = SList(block.splitlines())
3336 3336 print "Block assigned to '%s'" % par
3337 3337
3338 3338 def magic_cpaste(self, parameter_s=''):
3339 3339 """Allows you to paste & execute a pre-formatted code block from clipboard.
3340 3340
3341 3341 You must terminate the block with '--' (two minus-signs) alone on the
3342 3342 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3343 3343 is the new sentinel for this operation)
3344 3344
3345 3345 The block is dedented prior to execution to enable execution of method
3346 3346 definitions. '>' and '+' characters at the beginning of a line are
3347 3347 ignored, to allow pasting directly from e-mails, diff files and
3348 3348 doctests (the '...' continuation prompt is also stripped). The
3349 3349 executed block is also assigned to variable named 'pasted_block' for
3350 3350 later editing with '%edit pasted_block'.
3351 3351
3352 3352 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3353 3353 This assigns the pasted block to variable 'foo' as string, without
3354 3354 dedenting or executing it (preceding >>> and + is still stripped)
3355 3355
3356 3356 '%cpaste -r' re-executes the block previously entered by cpaste.
3357 3357
3358 3358 Do not be alarmed by garbled output on Windows (it's a readline bug).
3359 3359 Just press enter and type -- (and press enter again) and the block
3360 3360 will be what was just pasted.
3361 3361
3362 3362 IPython statements (magics, shell escapes) are not supported (yet).
3363 3363
3364 3364 See also
3365 3365 --------
3366 3366 paste: automatically pull code from clipboard.
3367 3367 """
3368 3368
3369 3369 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3370 3370 par = args.strip()
3371 3371 if opts.has_key('r'):
3372 3372 self._rerun_pasted()
3373 3373 return
3374 3374
3375 3375 sentinel = opts.get('s','--')
3376 3376
3377 3377 block = self._strip_pasted_lines_for_code(
3378 3378 self._get_pasted_lines(sentinel))
3379 3379
3380 3380 self._execute_block(block, par)
3381 3381
3382 3382 def magic_paste(self, parameter_s=''):
3383 3383 """Allows you to paste & execute a pre-formatted code block from clipboard.
3384 3384
3385 3385 The text is pulled directly from the clipboard without user
3386 3386 intervention.
3387 3387
3388 3388 The block is dedented prior to execution to enable execution of method
3389 3389 definitions. '>' and '+' characters at the beginning of a line are
3390 3390 ignored, to allow pasting directly from e-mails, diff files and
3391 3391 doctests (the '...' continuation prompt is also stripped). The
3392 3392 executed block is also assigned to variable named 'pasted_block' for
3393 3393 later editing with '%edit pasted_block'.
3394 3394
3395 3395 You can also pass a variable name as an argument, e.g. '%paste foo'.
3396 3396 This assigns the pasted block to variable 'foo' as string, without
3397 3397 dedenting or executing it (preceding >>> and + is still stripped)
3398 3398
3399 3399 '%paste -r' re-executes the block previously entered by cpaste.
3400 3400
3401 3401 IPython statements (magics, shell escapes) are not supported (yet).
3402 3402
3403 3403 See also
3404 3404 --------
3405 3405 cpaste: manually paste code into terminal until you mark its end.
3406 3406 """
3407 3407 opts,args = self.parse_options(parameter_s,'r:',mode='string')
3408 3408 par = args.strip()
3409 3409 if opts.has_key('r'):
3410 3410 self._rerun_pasted()
3411 3411 return
3412 3412
3413 3413 text = self.shell.hooks.clipboard_get()
3414 3414 block = self._strip_pasted_lines_for_code(text.splitlines())
3415 3415 self._execute_block(block, par)
3416 3416
3417 3417 def magic_quickref(self,arg):
3418 3418 """ Show a quick reference sheet """
3419 3419 import IPython.usage
3420 3420 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3421 3421
3422 3422 page(qr)
3423 3423
3424 3424 def magic_upgrade(self,arg):
3425 3425 """ Upgrade your IPython installation
3426 3426
3427 3427 This will copy the config files that don't yet exist in your
3428 3428 ipython dir from the system config dir. Use this after upgrading
3429 3429 IPython if you don't wish to delete your .ipython dir.
3430 3430
3431 3431 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3432 3432 new users)
3433 3433
3434 3434 """
3435 3435 ip = self.getapi()
3436 3436 ipinstallation = path(IPython.__file__).dirname()
3437 3437 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3438 3438 src_config = ipinstallation / 'UserConfig'
3439 3439 userdir = path(ip.options.ipythondir)
3440 3440 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3441 3441 print ">",cmd
3442 3442 shell(cmd)
3443 3443 if arg == '-nolegacy':
3444 3444 legacy = userdir.files('ipythonrc*')
3445 3445 print "Nuking legacy files:",legacy
3446 3446
3447 3447 [p.remove() for p in legacy]
3448 3448 suffix = (sys.platform == 'win32' and '.ini' or '')
3449 3449 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3450 3450
3451 3451
3452 3452 def magic_doctest_mode(self,parameter_s=''):
3453 3453 """Toggle doctest mode on and off.
3454 3454
3455 3455 This mode allows you to toggle the prompt behavior between normal
3456 3456 IPython prompts and ones that are as similar to the default IPython
3457 3457 interpreter as possible.
3458 3458
3459 3459 It also supports the pasting of code snippets that have leading '>>>'
3460 3460 and '...' prompts in them. This means that you can paste doctests from
3461 3461 files or docstrings (even if they have leading whitespace), and the
3462 3462 code will execute correctly. You can then use '%history -tn' to see
3463 3463 the translated history without line numbers; this will give you the
3464 3464 input after removal of all the leading prompts and whitespace, which
3465 3465 can be pasted back into an editor.
3466 3466
3467 3467 With these features, you can switch into this mode easily whenever you
3468 3468 need to do testing and changes to doctests, without having to leave
3469 3469 your existing IPython session.
3470 3470 """
3471 3471
3472 3472 # XXX - Fix this to have cleaner activate/deactivate calls.
3473 3473 from IPython.Extensions import InterpreterPasteInput as ipaste
3474 3474 from IPython.ipstruct import Struct
3475 3475
3476 3476 # Shorthands
3477 3477 shell = self.shell
3478 3478 oc = shell.outputcache
3479 3479 rc = shell.rc
3480 3480 meta = shell.meta
3481 3481 # dstore is a data store kept in the instance metadata bag to track any
3482 3482 # changes we make, so we can undo them later.
3483 3483 dstore = meta.setdefault('doctest_mode',Struct())
3484 3484 save_dstore = dstore.setdefault
3485 3485
3486 3486 # save a few values we'll need to recover later
3487 3487 mode = save_dstore('mode',False)
3488 3488 save_dstore('rc_pprint',rc.pprint)
3489 3489 save_dstore('xmode',shell.InteractiveTB.mode)
3490 3490 save_dstore('rc_separate_out',rc.separate_out)
3491 3491 save_dstore('rc_separate_out2',rc.separate_out2)
3492 3492 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3493 3493 save_dstore('rc_separate_in',rc.separate_in)
3494 3494
3495 3495 if mode == False:
3496 3496 # turn on
3497 3497 ipaste.activate_prefilter()
3498 3498
3499 3499 oc.prompt1.p_template = '>>> '
3500 3500 oc.prompt2.p_template = '... '
3501 3501 oc.prompt_out.p_template = ''
3502 3502
3503 3503 # Prompt separators like plain python
3504 3504 oc.input_sep = oc.prompt1.sep = ''
3505 3505 oc.output_sep = ''
3506 3506 oc.output_sep2 = ''
3507 3507
3508 3508 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3509 3509 oc.prompt_out.pad_left = False
3510 3510
3511 3511 rc.pprint = False
3512 3512
3513 3513 shell.magic_xmode('Plain')
3514 3514
3515 3515 else:
3516 3516 # turn off
3517 3517 ipaste.deactivate_prefilter()
3518 3518
3519 3519 oc.prompt1.p_template = rc.prompt_in1
3520 3520 oc.prompt2.p_template = rc.prompt_in2
3521 3521 oc.prompt_out.p_template = rc.prompt_out
3522 3522
3523 3523 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3524 3524
3525 3525 oc.output_sep = dstore.rc_separate_out
3526 3526 oc.output_sep2 = dstore.rc_separate_out2
3527 3527
3528 3528 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3529 3529 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3530 3530
3531 3531 rc.pprint = dstore.rc_pprint
3532 3532
3533 3533 shell.magic_xmode(dstore.xmode)
3534 3534
3535 3535 # Store new mode and inform
3536 3536 dstore.mode = bool(1-int(mode))
3537 3537 print 'Doctest mode is:',
3538 3538 print ['OFF','ON'][dstore.mode]
3539 3539
3540 3540 # end Magic
@@ -1,2873 +1,2873 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.4 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #
17 17 # Note: this code originally subclassed code.InteractiveConsole from the
18 18 # Python standard library. Over time, all of that class has been copied
19 19 # verbatim here for modifications which could not be accomplished by
20 20 # subclassing. At this point, there are no dependencies at all on the code
21 21 # module anymore (it is not even imported). The Python License (sec. 2)
22 22 # allows for this, but it's always nice to acknowledge credit where credit is
23 23 # due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 # Python standard modules
30 30 import __main__
31 31 import __builtin__
32 32 import StringIO
33 33 import bdb
34 34 import cPickle as pickle
35 35 import codeop
36 36 import exceptions
37 37 import glob
38 38 import inspect
39 39 import keyword
40 40 import new
41 41 import os
42 42 import pydoc
43 43 import re
44 44 import shutil
45 45 import string
46 46 import sys
47 47 import tempfile
48 48 import traceback
49 49 import types
50 50 from pprint import pprint, pformat
51 51
52 52 # IPython's own modules
53 53 #import IPython
54 54 from IPython import Debugger,OInspect,PyColorize,ultraTB
55 55 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
56 56 from IPython.Extensions import pickleshare
57 57 from IPython.FakeModule import FakeModule, init_fakemod_dict
58 58 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
59 59 from IPython.Logger import Logger
60 60 from IPython.Magic import Magic
61 61 from IPython.Prompts import CachedOutput
62 62 from IPython.ipstruct import Struct
63 63 from IPython.background_jobs import BackgroundJobManager
64 64 from IPython.usage import cmd_line_usage,interactive_usage
65 65 from IPython.genutils import *
66 66 from IPython.strdispatch import StrDispatch
67 67 import IPython.ipapi
68 68 import IPython.history
69 69 import IPython.prefilter as prefilter
70 70 import IPython.shadowns
71 71 # Globals
72 72
73 73 # store the builtin raw_input globally, and use this always, in case user code
74 74 # overwrites it (like wx.py.PyShell does)
75 75 raw_input_original = raw_input
76 76
77 77 # compiled regexps for autoindent management
78 78 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 79
80 80
81 81 #****************************************************************************
82 82 # Some utility function definitions
83 83
84 84 ini_spaces_re = re.compile(r'^(\s+)')
85 85
86 86 def num_ini_spaces(strng):
87 87 """Return the number of initial spaces in a string"""
88 88
89 89 ini_spaces = ini_spaces_re.match(strng)
90 90 if ini_spaces:
91 91 return ini_spaces.end()
92 92 else:
93 93 return 0
94 94
95 95 def softspace(file, newvalue):
96 96 """Copied from code.py, to remove the dependency"""
97 97
98 98 oldvalue = 0
99 99 try:
100 100 oldvalue = file.softspace
101 101 except AttributeError:
102 102 pass
103 103 try:
104 104 file.softspace = newvalue
105 105 except (AttributeError, TypeError):
106 106 # "attribute-less object" or "read-only attributes"
107 107 pass
108 108 return oldvalue
109 109
110 110
111 111 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
112 112 """Install or upgrade the user configuration directory.
113 113
114 114 Can be called when running for the first time or to upgrade the user's
115 115 .ipython/ directory.
116 116
117 117 Parameters
118 118 ----------
119 119 ipythondir : path
120 120 The directory to be used for installation/upgrade. In 'install' mode,
121 121 if this path already exists, the function exits immediately.
122 122
123 123 rc_suffix : str
124 124 Extension for the config files. On *nix platforms it is typically the
125 125 empty string, while Windows normally uses '.ini'.
126 126
127 127 mode : str, optional
128 128 Valid modes are 'install' and 'upgrade'.
129 129
130 130 interactive : bool, optional
131 131 If False, do not wait for user input on any errors. Normally after
132 132 printing its status information, this function waits for the user to
133 133 hit Return before proceeding. This is because the default use case is
134 134 when first installing the IPython configuration, so we want the user to
135 135 acknowledge the initial message, which contains some useful
136 136 information.
137 137 """
138 138
139 139 # For automatic use, deactivate all i/o
140 140 if interactive:
141 141 def wait():
142 142 try:
143 143 raw_input("Please press <RETURN> to start IPython.")
144 144 except EOFError:
145 145 print >> Term.cout
146 146 print '*'*70
147 147
148 148 def printf(s):
149 149 print s
150 150 else:
151 151 wait = lambda : None
152 152 printf = lambda s : None
153 153
154 154 # Install mode should be re-entrant: if the install dir already exists,
155 155 # bail out cleanly.
156 156 # XXX. This is too hasty to return. We need to check to make sure that
157 157 # all the expected config files and directories are actually there. We
158 158 # currently have a failure mode if someone deletes a needed config file
159 159 # but still has the ipythondir.
160 160 if mode == 'install' and os.path.isdir(ipythondir):
161 161 return
162 162
163 163 cwd = os.getcwd() # remember where we started
164 164 glb = glob.glob
165 165
166 166 printf('*'*70)
167 167 if mode == 'install':
168 168 printf(
169 169 """Welcome to IPython. I will try to create a personal configuration directory
170 170 where you can customize many aspects of IPython's functionality in:\n""")
171 171 else:
172 172 printf('I am going to upgrade your configuration in:')
173 173
174 174 printf(ipythondir)
175 175
176 176 rcdirend = os.path.join('IPython','UserConfig')
177 177 cfg = lambda d: os.path.join(d,rcdirend)
178 178 try:
179 179 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
180 180 printf("Initializing from configuration: %s" % rcdir)
181 181 except IndexError:
182 182 warning = """
183 183 Installation error. IPython's directory was not found.
184 184
185 185 Check the following:
186 186
187 187 The ipython/IPython directory should be in a directory belonging to your
188 188 PYTHONPATH environment variable (that is, it should be in a directory
189 189 belonging to sys.path). You can copy it explicitly there or just link to it.
190 190
191 191 IPython will create a minimal default configuration for you.
192 192
193 193 """
194 194 warn(warning)
195 195 wait()
196 196
197 197 if sys.platform =='win32':
198 198 inif = 'ipythonrc.ini'
199 199 else:
200 200 inif = 'ipythonrc'
201 201 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
202 202 inif : '# intentionally left blank' }
203 203 os.makedirs(ipythondir, mode = 0777)
204 204 for f, cont in minimal_setup.items():
205 205 # In 2.5, this can be more cleanly done using 'with'
206 206 fobj = file(ipythondir + '/' + f,'w')
207 207 fobj.write(cont)
208 208 fobj.close()
209 209
210 210 return
211 211
212 212 if mode == 'install':
213 213 try:
214 214 shutil.copytree(rcdir,ipythondir)
215 215 os.chdir(ipythondir)
216 216 rc_files = glb("ipythonrc*")
217 217 for rc_file in rc_files:
218 218 os.rename(rc_file,rc_file+rc_suffix)
219 219 except:
220 220 warning = """
221 221
222 222 There was a problem with the installation:
223 223 %s
224 224 Try to correct it or contact the developers if you think it's a bug.
225 225 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
226 226 warn(warning)
227 227 wait()
228 228 return
229 229
230 230 elif mode == 'upgrade':
231 231 try:
232 232 os.chdir(ipythondir)
233 233 except:
234 234 printf("""
235 235 Can not upgrade: changing to directory %s failed. Details:
236 236 %s
237 237 """ % (ipythondir,sys.exc_info()[1]) )
238 238 wait()
239 239 return
240 240 else:
241 241 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
242 242 for new_full_path in sources:
243 243 new_filename = os.path.basename(new_full_path)
244 244 if new_filename.startswith('ipythonrc'):
245 245 new_filename = new_filename + rc_suffix
246 246 # The config directory should only contain files, skip any
247 247 # directories which may be there (like CVS)
248 248 if os.path.isdir(new_full_path):
249 249 continue
250 250 if os.path.exists(new_filename):
251 251 old_file = new_filename+'.old'
252 252 if os.path.exists(old_file):
253 253 os.remove(old_file)
254 254 os.rename(new_filename,old_file)
255 255 shutil.copy(new_full_path,new_filename)
256 256 else:
257 257 raise ValueError('unrecognized mode for install: %r' % mode)
258 258
259 259 # Fix line-endings to those native to each platform in the config
260 260 # directory.
261 261 try:
262 262 os.chdir(ipythondir)
263 263 except:
264 264 printf("""
265 265 Problem: changing to directory %s failed.
266 266 Details:
267 267 %s
268 268
269 269 Some configuration files may have incorrect line endings. This should not
270 270 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
271 271 wait()
272 272 else:
273 273 for fname in glb('ipythonrc*'):
274 274 try:
275 275 native_line_ends(fname,backup=0)
276 276 except IOError:
277 277 pass
278 278
279 279 if mode == 'install':
280 280 printf("""
281 281 Successful installation!
282 282
283 283 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
284 284 IPython manual (there are both HTML and PDF versions supplied with the
285 285 distribution) to make sure that your system environment is properly configured
286 286 to take advantage of IPython's features.
287 287
288 288 Important note: the configuration system has changed! The old system is
289 289 still in place, but its setting may be partly overridden by the settings in
290 290 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
291 291 if some of the new settings bother you.
292 292
293 293 """)
294 294 else:
295 295 printf("""
296 296 Successful upgrade!
297 297
298 298 All files in your directory:
299 299 %(ipythondir)s
300 300 which would have been overwritten by the upgrade were backed up with a .old
301 301 extension. If you had made particular customizations in those files you may
302 302 want to merge them back into the new files.""" % locals() )
303 303 wait()
304 304 os.chdir(cwd)
305 305
306 306 #****************************************************************************
307 307 # Local use exceptions
308 308 class SpaceInInput(exceptions.Exception): pass
309 309
310 310
311 311 #****************************************************************************
312 312 # Local use classes
313 313 class Bunch: pass
314 314
315 315 class Undefined: pass
316 316
317 317 class Quitter(object):
318 318 """Simple class to handle exit, similar to Python 2.5's.
319 319
320 320 It handles exiting in an ipython-safe manner, which the one in Python 2.5
321 321 doesn't do (obviously, since it doesn't know about ipython)."""
322 322
323 323 def __init__(self,shell,name):
324 324 self.shell = shell
325 325 self.name = name
326 326
327 327 def __repr__(self):
328 328 return 'Type %s() to exit.' % self.name
329 329 __str__ = __repr__
330 330
331 331 def __call__(self):
332 332 self.shell.exit()
333 333
334 334 class InputList(list):
335 335 """Class to store user input.
336 336
337 337 It's basically a list, but slices return a string instead of a list, thus
338 338 allowing things like (assuming 'In' is an instance):
339 339
340 340 exec In[4:7]
341 341
342 342 or
343 343
344 344 exec In[5:9] + In[14] + In[21:25]"""
345 345
346 346 def __getslice__(self,i,j):
347 347 return ''.join(list.__getslice__(self,i,j))
348 348
349 349 class SyntaxTB(ultraTB.ListTB):
350 350 """Extension which holds some state: the last exception value"""
351 351
352 352 def __init__(self,color_scheme = 'NoColor'):
353 353 ultraTB.ListTB.__init__(self,color_scheme)
354 354 self.last_syntax_error = None
355 355
356 356 def __call__(self, etype, value, elist):
357 357 self.last_syntax_error = value
358 358 ultraTB.ListTB.__call__(self,etype,value,elist)
359 359
360 360 def clear_err_state(self):
361 361 """Return the current error state and clear it"""
362 362 e = self.last_syntax_error
363 363 self.last_syntax_error = None
364 364 return e
365 365
366 366 #****************************************************************************
367 367 # Main IPython class
368 368
369 369 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
370 370 # until a full rewrite is made. I've cleaned all cross-class uses of
371 371 # attributes and methods, but too much user code out there relies on the
372 372 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
373 373 #
374 374 # But at least now, all the pieces have been separated and we could, in
375 375 # principle, stop using the mixin. This will ease the transition to the
376 376 # chainsaw branch.
377 377
378 378 # For reference, the following is the list of 'self.foo' uses in the Magic
379 379 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
380 380 # class, to prevent clashes.
381 381
382 382 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
383 383 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
384 384 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
385 385 # 'self.value']
386 386
387 387 class InteractiveShell(object,Magic):
388 388 """An enhanced console for Python."""
389 389
390 390 # class attribute to indicate whether the class supports threads or not.
391 391 # Subclasses with thread support should override this as needed.
392 392 isthreaded = False
393 393
394 394 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
395 395 user_ns=None,user_global_ns=None,banner2='',
396 396 custom_exceptions=((),None),embedded=False):
397 397
398 398 # log system
399 399 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
400 400
401 401 # Job manager (for jobs run as background threads)
402 402 self.jobs = BackgroundJobManager()
403 403
404 404 # Store the actual shell's name
405 405 self.name = name
406 406 self.more = False
407 407
408 408 # We need to know whether the instance is meant for embedding, since
409 409 # global/local namespaces need to be handled differently in that case
410 410 self.embedded = embedded
411 411 if embedded:
412 412 # Control variable so users can, from within the embedded instance,
413 413 # permanently deactivate it.
414 414 self.embedded_active = True
415 415
416 416 # command compiler
417 417 self.compile = codeop.CommandCompiler()
418 418
419 419 # User input buffer
420 420 self.buffer = []
421 421
422 422 # Default name given in compilation of code
423 423 self.filename = '<ipython console>'
424 424
425 425 # Install our own quitter instead of the builtins. For python2.3-2.4,
426 426 # this brings in behavior like 2.5, and for 2.5 it's identical.
427 427 __builtin__.exit = Quitter(self,'exit')
428 428 __builtin__.quit = Quitter(self,'quit')
429 429
430 430 # Make an empty namespace, which extension writers can rely on both
431 431 # existing and NEVER being used by ipython itself. This gives them a
432 432 # convenient location for storing additional information and state
433 433 # their extensions may require, without fear of collisions with other
434 434 # ipython names that may develop later.
435 435 self.meta = Struct()
436 436
437 437 # Create the namespace where the user will operate. user_ns is
438 438 # normally the only one used, and it is passed to the exec calls as
439 439 # the locals argument. But we do carry a user_global_ns namespace
440 440 # given as the exec 'globals' argument, This is useful in embedding
441 441 # situations where the ipython shell opens in a context where the
442 442 # distinction between locals and globals is meaningful. For
443 443 # non-embedded contexts, it is just the same object as the user_ns dict.
444 444
445 445 # FIXME. For some strange reason, __builtins__ is showing up at user
446 446 # level as a dict instead of a module. This is a manual fix, but I
447 447 # should really track down where the problem is coming from. Alex
448 448 # Schmolck reported this problem first.
449 449
450 450 # A useful post by Alex Martelli on this topic:
451 451 # Re: inconsistent value from __builtins__
452 452 # Von: Alex Martelli <aleaxit@yahoo.com>
453 453 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
454 454 # Gruppen: comp.lang.python
455 455
456 456 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
457 457 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
458 458 # > <type 'dict'>
459 459 # > >>> print type(__builtins__)
460 460 # > <type 'module'>
461 461 # > Is this difference in return value intentional?
462 462
463 463 # Well, it's documented that '__builtins__' can be either a dictionary
464 464 # or a module, and it's been that way for a long time. Whether it's
465 465 # intentional (or sensible), I don't know. In any case, the idea is
466 466 # that if you need to access the built-in namespace directly, you
467 467 # should start with "import __builtin__" (note, no 's') which will
468 468 # definitely give you a module. Yeah, it's somewhat confusing:-(.
469 469
470 470 # These routines return properly built dicts as needed by the rest of
471 471 # the code, and can also be used by extension writers to generate
472 472 # properly initialized namespaces.
473 473 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
474 474 user_global_ns)
475 475
476 476 # Assign namespaces
477 477 # This is the namespace where all normal user variables live
478 478 self.user_ns = user_ns
479 479 self.user_global_ns = user_global_ns
480 480
481 481 # An auxiliary namespace that checks what parts of the user_ns were
482 482 # loaded at startup, so we can list later only variables defined in
483 483 # actual interactive use. Since it is always a subset of user_ns, it
484 484 # doesn't need to be seaparately tracked in the ns_table
485 485 self.user_config_ns = {}
486 486
487 487 # A namespace to keep track of internal data structures to prevent
488 488 # them from cluttering user-visible stuff. Will be updated later
489 489 self.internal_ns = {}
490 490
491 491 # Namespace of system aliases. Each entry in the alias
492 492 # table must be a 2-tuple of the form (N,name), where N is the number
493 493 # of positional arguments of the alias.
494 494 self.alias_table = {}
495 495
496 496 # Now that FakeModule produces a real module, we've run into a nasty
497 497 # problem: after script execution (via %run), the module where the user
498 498 # code ran is deleted. Now that this object is a true module (needed
499 499 # so docetst and other tools work correctly), the Python module
500 500 # teardown mechanism runs over it, and sets to None every variable
501 501 # present in that module. Top-level references to objects from the
502 502 # script survive, because the user_ns is updated with them. However,
503 503 # calling functions defined in the script that use other things from
504 504 # the script will fail, because the function's closure had references
505 505 # to the original objects, which are now all None. So we must protect
506 506 # these modules from deletion by keeping a cache.
507 507 #
508 508 # To avoid keeping stale modules around (we only need the one from the
509 509 # last run), we use a dict keyed with the full path to the script, so
510 510 # only the last version of the module is held in the cache. Note,
511 511 # however, that we must cache the module *namespace contents* (their
512 512 # __dict__). Because if we try to cache the actual modules, old ones
513 513 # (uncached) could be destroyed while still holding references (such as
514 514 # those held by GUI objects that tend to be long-lived)>
515 515 #
516 516 # The %reset command will flush this cache. See the cache_main_mod()
517 517 # and clear_main_mod_cache() methods for details on use.
518 518
519 519 # This is the cache used for 'main' namespaces
520 520 self._main_ns_cache = {}
521 521 # And this is the single instance of FakeModule whose __dict__ we keep
522 522 # copying and clearing for reuse on each %run
523 523 self._user_main_module = FakeModule()
524 524
525 525 # A table holding all the namespaces IPython deals with, so that
526 526 # introspection facilities can search easily.
527 527 self.ns_table = {'user':user_ns,
528 528 'user_global':user_global_ns,
529 529 'alias':self.alias_table,
530 530 'internal':self.internal_ns,
531 531 'builtin':__builtin__.__dict__
532 532 }
533 533
534 534 # Similarly, track all namespaces where references can be held and that
535 535 # we can safely clear (so it can NOT include builtin). This one can be
536 536 # a simple list.
537 537 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
538 538 self.alias_table, self.internal_ns,
539 539 self._main_ns_cache ]
540 540
541 541 # We need to insert into sys.modules something that looks like a
542 542 # module but which accesses the IPython namespace, for shelve and
543 543 # pickle to work interactively. Normally they rely on getting
544 544 # everything out of __main__, but for embedding purposes each IPython
545 545 # instance has its own private namespace, so we can't go shoving
546 546 # everything into __main__.
547 547
548 548 # note, however, that we should only do this for non-embedded
549 549 # ipythons, which really mimic the __main__.__dict__ with their own
550 550 # namespace. Embedded instances, on the other hand, should not do
551 551 # this because they need to manage the user local/global namespaces
552 552 # only, but they live within a 'normal' __main__ (meaning, they
553 553 # shouldn't overtake the execution environment of the script they're
554 554 # embedded in).
555 555
556 556 if not embedded:
557 557 try:
558 558 main_name = self.user_ns['__name__']
559 559 except KeyError:
560 560 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
561 561 else:
562 562 #print "pickle hack in place" # dbg
563 563 #print 'main_name:',main_name # dbg
564 564 sys.modules[main_name] = FakeModule(self.user_ns)
565 565
566 566 # List of input with multi-line handling.
567 567 self.input_hist = InputList()
568 568 # This one will hold the 'raw' input history, without any
569 569 # pre-processing. This will allow users to retrieve the input just as
570 570 # it was exactly typed in by the user, with %hist -r.
571 571 self.input_hist_raw = InputList()
572 572
573 573 # list of visited directories
574 574 try:
575 575 self.dir_hist = [os.getcwd()]
576 576 except OSError:
577 577 self.dir_hist = []
578 578
579 579 # dict of output history
580 580 self.output_hist = {}
581 581
582 582 # Get system encoding at startup time. Certain terminals (like Emacs
583 583 # under Win32 have it set to None, and we need to have a known valid
584 584 # encoding to use in the raw_input() method
585 585 try:
586 586 self.stdin_encoding = sys.stdin.encoding or 'ascii'
587 587 except AttributeError:
588 588 self.stdin_encoding = 'ascii'
589 589
590 590 # dict of things NOT to alias (keywords, builtins and some magics)
591 591 no_alias = {}
592 592 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
593 593 for key in keyword.kwlist + no_alias_magics:
594 594 no_alias[key] = 1
595 595 no_alias.update(__builtin__.__dict__)
596 596 self.no_alias = no_alias
597 597
598 598 # Object variable to store code object waiting execution. This is
599 599 # used mainly by the multithreaded shells, but it can come in handy in
600 600 # other situations. No need to use a Queue here, since it's a single
601 601 # item which gets cleared once run.
602 602 self.code_to_run = None
603 603
604 604 # escapes for automatic behavior on the command line
605 605 self.ESC_SHELL = '!'
606 606 self.ESC_SH_CAP = '!!'
607 607 self.ESC_HELP = '?'
608 608 self.ESC_MAGIC = '%'
609 609 self.ESC_QUOTE = ','
610 610 self.ESC_QUOTE2 = ';'
611 611 self.ESC_PAREN = '/'
612 612
613 613 # And their associated handlers
614 614 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
615 615 self.ESC_QUOTE : self.handle_auto,
616 616 self.ESC_QUOTE2 : self.handle_auto,
617 617 self.ESC_MAGIC : self.handle_magic,
618 618 self.ESC_HELP : self.handle_help,
619 619 self.ESC_SHELL : self.handle_shell_escape,
620 620 self.ESC_SH_CAP : self.handle_shell_escape,
621 621 }
622 622
623 623 # class initializations
624 624 Magic.__init__(self,self)
625 625
626 626 # Python source parser/formatter for syntax highlighting
627 627 pyformat = PyColorize.Parser().format
628 628 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
629 629
630 630 # hooks holds pointers used for user-side customizations
631 631 self.hooks = Struct()
632 632
633 633 self.strdispatchers = {}
634 634
635 635 # Set all default hooks, defined in the IPython.hooks module.
636 636 hooks = IPython.hooks
637 637 for hook_name in hooks.__all__:
638 638 # default hooks have priority 100, i.e. low; user hooks should have
639 639 # 0-100 priority
640 640 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
641 641 #print "bound hook",hook_name
642 642
643 643 # Flag to mark unconditional exit
644 644 self.exit_now = False
645 645
646 646 self.usage_min = """\
647 647 An enhanced console for Python.
648 648 Some of its features are:
649 649 - Readline support if the readline library is present.
650 650 - Tab completion in the local namespace.
651 651 - Logging of input, see command-line options.
652 652 - System shell escape via ! , eg !ls.
653 653 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
654 654 - Keeps track of locally defined variables via %who, %whos.
655 655 - Show object information with a ? eg ?x or x? (use ?? for more info).
656 656 """
657 657 if usage: self.usage = usage
658 658 else: self.usage = self.usage_min
659 659
660 660 # Storage
661 661 self.rc = rc # This will hold all configuration information
662 662 self.pager = 'less'
663 663 # temporary files used for various purposes. Deleted at exit.
664 664 self.tempfiles = []
665 665
666 666 # Keep track of readline usage (later set by init_readline)
667 667 self.has_readline = False
668 668
669 669 # template for logfile headers. It gets resolved at runtime by the
670 670 # logstart method.
671 671 self.loghead_tpl = \
672 672 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
673 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
673 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW -* coding: %s *-
674 674 #log# opts = %s
675 675 #log# args = %s
676 676 #log# It is safe to make manual edits below here.
677 677 #log#-----------------------------------------------------------------------
678 678 """
679 679 # for pushd/popd management
680 680 try:
681 681 self.home_dir = get_home_dir()
682 682 except HomeDirError,msg:
683 683 fatal(msg)
684 684
685 685 self.dir_stack = []
686 686
687 687 # Functions to call the underlying shell.
688 688
689 689 # The first is similar to os.system, but it doesn't return a value,
690 690 # and it allows interpolation of variables in the user's namespace.
691 691 self.system = lambda cmd: \
692 692 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
693 693
694 694 # These are for getoutput and getoutputerror:
695 695 self.getoutput = lambda cmd: \
696 696 getoutput(self.var_expand(cmd,depth=2),
697 697 header=self.rc.system_header,
698 698 verbose=self.rc.system_verbose)
699 699
700 700 self.getoutputerror = lambda cmd: \
701 701 getoutputerror(self.var_expand(cmd,depth=2),
702 702 header=self.rc.system_header,
703 703 verbose=self.rc.system_verbose)
704 704
705 705
706 706 # keep track of where we started running (mainly for crash post-mortem)
707 707 self.starting_dir = os.getcwd()
708 708
709 709 # Various switches which can be set
710 710 self.CACHELENGTH = 5000 # this is cheap, it's just text
711 711 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
712 712 self.banner2 = banner2
713 713
714 714 # TraceBack handlers:
715 715
716 716 # Syntax error handler.
717 717 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
718 718
719 719 # The interactive one is initialized with an offset, meaning we always
720 720 # want to remove the topmost item in the traceback, which is our own
721 721 # internal code. Valid modes: ['Plain','Context','Verbose']
722 722 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
723 723 color_scheme='NoColor',
724 724 tb_offset = 1)
725 725
726 726 # IPython itself shouldn't crash. This will produce a detailed
727 727 # post-mortem if it does. But we only install the crash handler for
728 728 # non-threaded shells, the threaded ones use a normal verbose reporter
729 729 # and lose the crash handler. This is because exceptions in the main
730 730 # thread (such as in GUI code) propagate directly to sys.excepthook,
731 731 # and there's no point in printing crash dumps for every user exception.
732 732 if self.isthreaded:
733 733 ipCrashHandler = ultraTB.FormattedTB()
734 734 else:
735 735 from IPython import CrashHandler
736 736 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
737 737 self.set_crash_handler(ipCrashHandler)
738 738
739 739 # and add any custom exception handlers the user may have specified
740 740 self.set_custom_exc(*custom_exceptions)
741 741
742 742 # indentation management
743 743 self.autoindent = False
744 744 self.indent_current_nsp = 0
745 745
746 746 # Make some aliases automatically
747 747 # Prepare list of shell aliases to auto-define
748 748 if os.name == 'posix':
749 749 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
750 750 'mv mv -i','rm rm -i','cp cp -i',
751 751 'cat cat','less less','clear clear',
752 752 # a better ls
753 753 'ls ls -F',
754 754 # long ls
755 755 'll ls -lF')
756 756 # Extra ls aliases with color, which need special treatment on BSD
757 757 # variants
758 758 ls_extra = ( # color ls
759 759 'lc ls -F -o --color',
760 760 # ls normal files only
761 761 'lf ls -F -o --color %l | grep ^-',
762 762 # ls symbolic links
763 763 'lk ls -F -o --color %l | grep ^l',
764 764 # directories or links to directories,
765 765 'ldir ls -F -o --color %l | grep /$',
766 766 # things which are executable
767 767 'lx ls -F -o --color %l | grep ^-..x',
768 768 )
769 769 # The BSDs don't ship GNU ls, so they don't understand the
770 770 # --color switch out of the box
771 771 if 'bsd' in sys.platform:
772 772 ls_extra = ( # ls normal files only
773 773 'lf ls -lF | grep ^-',
774 774 # ls symbolic links
775 775 'lk ls -lF | grep ^l',
776 776 # directories or links to directories,
777 777 'ldir ls -lF | grep /$',
778 778 # things which are executable
779 779 'lx ls -lF | grep ^-..x',
780 780 )
781 781 auto_alias = auto_alias + ls_extra
782 782 elif os.name in ['nt','dos']:
783 783 auto_alias = ('ls dir /on',
784 784 'ddir dir /ad /on', 'ldir dir /ad /on',
785 785 'mkdir mkdir','rmdir rmdir','echo echo',
786 786 'ren ren','cls cls','copy copy')
787 787 else:
788 788 auto_alias = ()
789 789 self.auto_alias = [s.split(None,1) for s in auto_alias]
790 790
791 791 # Produce a public API instance
792 792 self.api = IPython.ipapi.IPApi(self)
793 793
794 794 # Initialize all user-visible namespaces
795 795 self.init_namespaces()
796 796
797 797 # Call the actual (public) initializer
798 798 self.init_auto_alias()
799 799
800 800 # track which builtins we add, so we can clean up later
801 801 self.builtins_added = {}
802 802 # This method will add the necessary builtins for operation, but
803 803 # tracking what it did via the builtins_added dict.
804 804
805 805 #TODO: remove this, redundant
806 806 self.add_builtins()
807 807 # end __init__
808 808
809 809 def var_expand(self,cmd,depth=0):
810 810 """Expand python variables in a string.
811 811
812 812 The depth argument indicates how many frames above the caller should
813 813 be walked to look for the local namespace where to expand variables.
814 814
815 815 The global namespace for expansion is always the user's interactive
816 816 namespace.
817 817 """
818 818
819 819 return str(ItplNS(cmd,
820 820 self.user_ns, # globals
821 821 # Skip our own frame in searching for locals:
822 822 sys._getframe(depth+1).f_locals # locals
823 823 ))
824 824
825 825 def pre_config_initialization(self):
826 826 """Pre-configuration init method
827 827
828 828 This is called before the configuration files are processed to
829 829 prepare the services the config files might need.
830 830
831 831 self.rc already has reasonable default values at this point.
832 832 """
833 833 rc = self.rc
834 834 try:
835 835 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
836 836 except exceptions.UnicodeDecodeError:
837 837 print "Your ipythondir can't be decoded to unicode!"
838 838 print "Please set HOME environment variable to something that"
839 839 print r"only has ASCII characters, e.g. c:\home"
840 840 print "Now it is",rc.ipythondir
841 841 sys.exit()
842 842 self.shadowhist = IPython.history.ShadowHist(self.db)
843 843
844 844 def post_config_initialization(self):
845 845 """Post configuration init method
846 846
847 847 This is called after the configuration files have been processed to
848 848 'finalize' the initialization."""
849 849
850 850 rc = self.rc
851 851
852 852 # Object inspector
853 853 self.inspector = OInspect.Inspector(OInspect.InspectColors,
854 854 PyColorize.ANSICodeColors,
855 855 'NoColor',
856 856 rc.object_info_string_level)
857 857
858 858 self.rl_next_input = None
859 859 self.rl_do_indent = False
860 860 # Load readline proper
861 861 if rc.readline:
862 862 self.init_readline()
863 863
864 864 # local shortcut, this is used a LOT
865 865 self.log = self.logger.log
866 866
867 867 # Initialize cache, set in/out prompts and printing system
868 868 self.outputcache = CachedOutput(self,
869 869 rc.cache_size,
870 870 rc.pprint,
871 871 input_sep = rc.separate_in,
872 872 output_sep = rc.separate_out,
873 873 output_sep2 = rc.separate_out2,
874 874 ps1 = rc.prompt_in1,
875 875 ps2 = rc.prompt_in2,
876 876 ps_out = rc.prompt_out,
877 877 pad_left = rc.prompts_pad_left)
878 878
879 879 # user may have over-ridden the default print hook:
880 880 try:
881 881 self.outputcache.__class__.display = self.hooks.display
882 882 except AttributeError:
883 883 pass
884 884
885 885 # I don't like assigning globally to sys, because it means when
886 886 # embedding instances, each embedded instance overrides the previous
887 887 # choice. But sys.displayhook seems to be called internally by exec,
888 888 # so I don't see a way around it. We first save the original and then
889 889 # overwrite it.
890 890 self.sys_displayhook = sys.displayhook
891 891 sys.displayhook = self.outputcache
892 892
893 893 # Do a proper resetting of doctest, including the necessary displayhook
894 894 # monkeypatching
895 895 try:
896 896 doctest_reload()
897 897 except ImportError:
898 898 warn("doctest module does not exist.")
899 899
900 900 # Set user colors (don't do it in the constructor above so that it
901 901 # doesn't crash if colors option is invalid)
902 902 self.magic_colors(rc.colors)
903 903
904 904 # Set calling of pdb on exceptions
905 905 self.call_pdb = rc.pdb
906 906
907 907 # Load user aliases
908 908 for alias in rc.alias:
909 909 self.magic_alias(alias)
910 910
911 911 self.hooks.late_startup_hook()
912 912
913 913 for cmd in self.rc.autoexec:
914 914 #print "autoexec>",cmd #dbg
915 915 self.api.runlines(cmd)
916 916
917 917 batchrun = False
918 918 for batchfile in [path(arg) for arg in self.rc.args
919 919 if arg.lower().endswith('.ipy')]:
920 920 if not batchfile.isfile():
921 921 print "No such batch file:", batchfile
922 922 continue
923 923 self.api.runlines(batchfile.text())
924 924 batchrun = True
925 925 # without -i option, exit after running the batch file
926 926 if batchrun and not self.rc.interact:
927 927 self.ask_exit()
928 928
929 929 def init_namespaces(self):
930 930 """Initialize all user-visible namespaces to their minimum defaults.
931 931
932 932 Certain history lists are also initialized here, as they effectively
933 933 act as user namespaces.
934 934
935 935 Notes
936 936 -----
937 937 All data structures here are only filled in, they are NOT reset by this
938 938 method. If they were not empty before, data will simply be added to
939 939 therm.
940 940 """
941 941 # The user namespace MUST have a pointer to the shell itself.
942 942 self.user_ns[self.name] = self
943 943
944 944 # Store the public api instance
945 945 self.user_ns['_ip'] = self.api
946 946
947 947 # make global variables for user access to the histories
948 948 self.user_ns['_ih'] = self.input_hist
949 949 self.user_ns['_oh'] = self.output_hist
950 950 self.user_ns['_dh'] = self.dir_hist
951 951
952 952 # user aliases to input and output histories
953 953 self.user_ns['In'] = self.input_hist
954 954 self.user_ns['Out'] = self.output_hist
955 955
956 956 self.user_ns['_sh'] = IPython.shadowns
957 957
958 958 # Fill the history zero entry, user counter starts at 1
959 959 self.input_hist.append('\n')
960 960 self.input_hist_raw.append('\n')
961 961
962 962 def add_builtins(self):
963 963 """Store ipython references into the builtin namespace.
964 964
965 965 Some parts of ipython operate via builtins injected here, which hold a
966 966 reference to IPython itself."""
967 967
968 968 # TODO: deprecate all of these, they are unsafe
969 969 builtins_new = dict(__IPYTHON__ = self,
970 970 ip_set_hook = self.set_hook,
971 971 jobs = self.jobs,
972 972 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
973 973 ipalias = wrap_deprecated(self.ipalias),
974 974 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
975 975 #_ip = self.api
976 976 )
977 977 for biname,bival in builtins_new.items():
978 978 try:
979 979 # store the orignal value so we can restore it
980 980 self.builtins_added[biname] = __builtin__.__dict__[biname]
981 981 except KeyError:
982 982 # or mark that it wasn't defined, and we'll just delete it at
983 983 # cleanup
984 984 self.builtins_added[biname] = Undefined
985 985 __builtin__.__dict__[biname] = bival
986 986
987 987 # Keep in the builtins a flag for when IPython is active. We set it
988 988 # with setdefault so that multiple nested IPythons don't clobber one
989 989 # another. Each will increase its value by one upon being activated,
990 990 # which also gives us a way to determine the nesting level.
991 991 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
992 992
993 993 def clean_builtins(self):
994 994 """Remove any builtins which might have been added by add_builtins, or
995 995 restore overwritten ones to their previous values."""
996 996 for biname,bival in self.builtins_added.items():
997 997 if bival is Undefined:
998 998 del __builtin__.__dict__[biname]
999 999 else:
1000 1000 __builtin__.__dict__[biname] = bival
1001 1001 self.builtins_added.clear()
1002 1002
1003 1003 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1004 1004 """set_hook(name,hook) -> sets an internal IPython hook.
1005 1005
1006 1006 IPython exposes some of its internal API as user-modifiable hooks. By
1007 1007 adding your function to one of these hooks, you can modify IPython's
1008 1008 behavior to call at runtime your own routines."""
1009 1009
1010 1010 # At some point in the future, this should validate the hook before it
1011 1011 # accepts it. Probably at least check that the hook takes the number
1012 1012 # of args it's supposed to.
1013 1013
1014 1014 f = new.instancemethod(hook,self,self.__class__)
1015 1015
1016 1016 # check if the hook is for strdispatcher first
1017 1017 if str_key is not None:
1018 1018 sdp = self.strdispatchers.get(name, StrDispatch())
1019 1019 sdp.add_s(str_key, f, priority )
1020 1020 self.strdispatchers[name] = sdp
1021 1021 return
1022 1022 if re_key is not None:
1023 1023 sdp = self.strdispatchers.get(name, StrDispatch())
1024 1024 sdp.add_re(re.compile(re_key), f, priority )
1025 1025 self.strdispatchers[name] = sdp
1026 1026 return
1027 1027
1028 1028 dp = getattr(self.hooks, name, None)
1029 1029 if name not in IPython.hooks.__all__:
1030 1030 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
1031 1031 if not dp:
1032 1032 dp = IPython.hooks.CommandChainDispatcher()
1033 1033
1034 1034 try:
1035 1035 dp.add(f,priority)
1036 1036 except AttributeError:
1037 1037 # it was not commandchain, plain old func - replace
1038 1038 dp = f
1039 1039
1040 1040 setattr(self.hooks,name, dp)
1041 1041
1042 1042
1043 1043 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1044 1044
1045 1045 def set_crash_handler(self,crashHandler):
1046 1046 """Set the IPython crash handler.
1047 1047
1048 1048 This must be a callable with a signature suitable for use as
1049 1049 sys.excepthook."""
1050 1050
1051 1051 # Install the given crash handler as the Python exception hook
1052 1052 sys.excepthook = crashHandler
1053 1053
1054 1054 # The instance will store a pointer to this, so that runtime code
1055 1055 # (such as magics) can access it. This is because during the
1056 1056 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1057 1057 # frameworks).
1058 1058 self.sys_excepthook = sys.excepthook
1059 1059
1060 1060
1061 1061 def set_custom_exc(self,exc_tuple,handler):
1062 1062 """set_custom_exc(exc_tuple,handler)
1063 1063
1064 1064 Set a custom exception handler, which will be called if any of the
1065 1065 exceptions in exc_tuple occur in the mainloop (specifically, in the
1066 1066 runcode() method.
1067 1067
1068 1068 Inputs:
1069 1069
1070 1070 - exc_tuple: a *tuple* of valid exceptions to call the defined
1071 1071 handler for. It is very important that you use a tuple, and NOT A
1072 1072 LIST here, because of the way Python's except statement works. If
1073 1073 you only want to trap a single exception, use a singleton tuple:
1074 1074
1075 1075 exc_tuple == (MyCustomException,)
1076 1076
1077 1077 - handler: this must be defined as a function with the following
1078 1078 basic interface: def my_handler(self,etype,value,tb).
1079 1079
1080 1080 This will be made into an instance method (via new.instancemethod)
1081 1081 of IPython itself, and it will be called if any of the exceptions
1082 1082 listed in the exc_tuple are caught. If the handler is None, an
1083 1083 internal basic one is used, which just prints basic info.
1084 1084
1085 1085 WARNING: by putting in your own exception handler into IPython's main
1086 1086 execution loop, you run a very good chance of nasty crashes. This
1087 1087 facility should only be used if you really know what you are doing."""
1088 1088
1089 1089 assert type(exc_tuple)==type(()) , \
1090 1090 "The custom exceptions must be given AS A TUPLE."
1091 1091
1092 1092 def dummy_handler(self,etype,value,tb):
1093 1093 print '*** Simple custom exception handler ***'
1094 1094 print 'Exception type :',etype
1095 1095 print 'Exception value:',value
1096 1096 print 'Traceback :',tb
1097 1097 print 'Source code :','\n'.join(self.buffer)
1098 1098
1099 1099 if handler is None: handler = dummy_handler
1100 1100
1101 1101 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1102 1102 self.custom_exceptions = exc_tuple
1103 1103
1104 1104 def set_custom_completer(self,completer,pos=0):
1105 1105 """set_custom_completer(completer,pos=0)
1106 1106
1107 1107 Adds a new custom completer function.
1108 1108
1109 1109 The position argument (defaults to 0) is the index in the completers
1110 1110 list where you want the completer to be inserted."""
1111 1111
1112 1112 newcomp = new.instancemethod(completer,self.Completer,
1113 1113 self.Completer.__class__)
1114 1114 self.Completer.matchers.insert(pos,newcomp)
1115 1115
1116 1116 def set_completer(self):
1117 1117 """reset readline's completer to be our own."""
1118 1118 self.readline.set_completer(self.Completer.complete)
1119 1119
1120 1120 def _get_call_pdb(self):
1121 1121 return self._call_pdb
1122 1122
1123 1123 def _set_call_pdb(self,val):
1124 1124
1125 1125 if val not in (0,1,False,True):
1126 1126 raise ValueError,'new call_pdb value must be boolean'
1127 1127
1128 1128 # store value in instance
1129 1129 self._call_pdb = val
1130 1130
1131 1131 # notify the actual exception handlers
1132 1132 self.InteractiveTB.call_pdb = val
1133 1133 if self.isthreaded:
1134 1134 try:
1135 1135 self.sys_excepthook.call_pdb = val
1136 1136 except:
1137 1137 warn('Failed to activate pdb for threaded exception handler')
1138 1138
1139 1139 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1140 1140 'Control auto-activation of pdb at exceptions')
1141 1141
1142 1142 # These special functions get installed in the builtin namespace, to
1143 1143 # provide programmatic (pure python) access to magics, aliases and system
1144 1144 # calls. This is important for logging, user scripting, and more.
1145 1145
1146 1146 # We are basically exposing, via normal python functions, the three
1147 1147 # mechanisms in which ipython offers special call modes (magics for
1148 1148 # internal control, aliases for direct system access via pre-selected
1149 1149 # names, and !cmd for calling arbitrary system commands).
1150 1150
1151 1151 def ipmagic(self,arg_s):
1152 1152 """Call a magic function by name.
1153 1153
1154 1154 Input: a string containing the name of the magic function to call and any
1155 1155 additional arguments to be passed to the magic.
1156 1156
1157 1157 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1158 1158 prompt:
1159 1159
1160 1160 In[1]: %name -opt foo bar
1161 1161
1162 1162 To call a magic without arguments, simply use ipmagic('name').
1163 1163
1164 1164 This provides a proper Python function to call IPython's magics in any
1165 1165 valid Python code you can type at the interpreter, including loops and
1166 1166 compound statements. It is added by IPython to the Python builtin
1167 1167 namespace upon initialization."""
1168 1168
1169 1169 args = arg_s.split(' ',1)
1170 1170 magic_name = args[0]
1171 1171 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1172 1172
1173 1173 try:
1174 1174 magic_args = args[1]
1175 1175 except IndexError:
1176 1176 magic_args = ''
1177 1177 fn = getattr(self,'magic_'+magic_name,None)
1178 1178 if fn is None:
1179 1179 error("Magic function `%s` not found." % magic_name)
1180 1180 else:
1181 1181 magic_args = self.var_expand(magic_args,1)
1182 1182 return fn(magic_args)
1183 1183
1184 1184 def ipalias(self,arg_s):
1185 1185 """Call an alias by name.
1186 1186
1187 1187 Input: a string containing the name of the alias to call and any
1188 1188 additional arguments to be passed to the magic.
1189 1189
1190 1190 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1191 1191 prompt:
1192 1192
1193 1193 In[1]: name -opt foo bar
1194 1194
1195 1195 To call an alias without arguments, simply use ipalias('name').
1196 1196
1197 1197 This provides a proper Python function to call IPython's aliases in any
1198 1198 valid Python code you can type at the interpreter, including loops and
1199 1199 compound statements. It is added by IPython to the Python builtin
1200 1200 namespace upon initialization."""
1201 1201
1202 1202 args = arg_s.split(' ',1)
1203 1203 alias_name = args[0]
1204 1204 try:
1205 1205 alias_args = args[1]
1206 1206 except IndexError:
1207 1207 alias_args = ''
1208 1208 if alias_name in self.alias_table:
1209 1209 self.call_alias(alias_name,alias_args)
1210 1210 else:
1211 1211 error("Alias `%s` not found." % alias_name)
1212 1212
1213 1213 def ipsystem(self,arg_s):
1214 1214 """Make a system call, using IPython."""
1215 1215
1216 1216 self.system(arg_s)
1217 1217
1218 1218 def complete(self,text):
1219 1219 """Return a sorted list of all possible completions on text.
1220 1220
1221 1221 Inputs:
1222 1222
1223 1223 - text: a string of text to be completed on.
1224 1224
1225 1225 This is a wrapper around the completion mechanism, similar to what
1226 1226 readline does at the command line when the TAB key is hit. By
1227 1227 exposing it as a method, it can be used by other non-readline
1228 1228 environments (such as GUIs) for text completion.
1229 1229
1230 1230 Simple usage example:
1231 1231
1232 1232 In [7]: x = 'hello'
1233 1233
1234 1234 In [8]: x
1235 1235 Out[8]: 'hello'
1236 1236
1237 1237 In [9]: print x
1238 1238 hello
1239 1239
1240 1240 In [10]: _ip.IP.complete('x.l')
1241 1241 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1242 1242 """
1243 1243
1244 1244 complete = self.Completer.complete
1245 1245 state = 0
1246 1246 # use a dict so we get unique keys, since ipyhton's multiple
1247 1247 # completers can return duplicates. When we make 2.4 a requirement,
1248 1248 # start using sets instead, which are faster.
1249 1249 comps = {}
1250 1250 while True:
1251 1251 newcomp = complete(text,state,line_buffer=text)
1252 1252 if newcomp is None:
1253 1253 break
1254 1254 comps[newcomp] = 1
1255 1255 state += 1
1256 1256 outcomps = comps.keys()
1257 1257 outcomps.sort()
1258 1258 #print "T:",text,"OC:",outcomps # dbg
1259 1259 #print "vars:",self.user_ns.keys()
1260 1260 return outcomps
1261 1261
1262 1262 def set_completer_frame(self, frame=None):
1263 1263 if not self.has_readline:
1264 1264 return
1265 1265 if frame:
1266 1266 self.Completer.namespace = frame.f_locals
1267 1267 self.Completer.global_namespace = frame.f_globals
1268 1268 else:
1269 1269 self.Completer.namespace = self.user_ns
1270 1270 self.Completer.global_namespace = self.user_global_ns
1271 1271
1272 1272 def init_auto_alias(self):
1273 1273 """Define some aliases automatically.
1274 1274
1275 1275 These are ALL parameter-less aliases"""
1276 1276
1277 1277 for alias,cmd in self.auto_alias:
1278 1278 self.getapi().defalias(alias,cmd)
1279 1279
1280 1280
1281 1281 def alias_table_validate(self,verbose=0):
1282 1282 """Update information about the alias table.
1283 1283
1284 1284 In particular, make sure no Python keywords/builtins are in it."""
1285 1285
1286 1286 no_alias = self.no_alias
1287 1287 for k in self.alias_table.keys():
1288 1288 if k in no_alias:
1289 1289 del self.alias_table[k]
1290 1290 if verbose:
1291 1291 print ("Deleting alias <%s>, it's a Python "
1292 1292 "keyword or builtin." % k)
1293 1293
1294 1294 def set_autoindent(self,value=None):
1295 1295 """Set the autoindent flag, checking for readline support.
1296 1296
1297 1297 If called with no arguments, it acts as a toggle."""
1298 1298
1299 1299 if not self.has_readline:
1300 1300 if os.name == 'posix':
1301 1301 warn("The auto-indent feature requires the readline library")
1302 1302 self.autoindent = 0
1303 1303 return
1304 1304 if value is None:
1305 1305 self.autoindent = not self.autoindent
1306 1306 else:
1307 1307 self.autoindent = value
1308 1308
1309 1309 def rc_set_toggle(self,rc_field,value=None):
1310 1310 """Set or toggle a field in IPython's rc config. structure.
1311 1311
1312 1312 If called with no arguments, it acts as a toggle.
1313 1313
1314 1314 If called with a non-existent field, the resulting AttributeError
1315 1315 exception will propagate out."""
1316 1316
1317 1317 rc_val = getattr(self.rc,rc_field)
1318 1318 if value is None:
1319 1319 value = not rc_val
1320 1320 setattr(self.rc,rc_field,value)
1321 1321
1322 1322 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1323 1323 """Install the user configuration directory.
1324 1324
1325 1325 Notes
1326 1326 -----
1327 1327 DEPRECATED: use the top-level user_setup() function instead.
1328 1328 """
1329 1329 return user_setup(ipythondir,rc_suffix,mode)
1330 1330
1331 1331 def atexit_operations(self):
1332 1332 """This will be executed at the time of exit.
1333 1333
1334 1334 Saving of persistent data should be performed here. """
1335 1335
1336 1336 #print '*** IPython exit cleanup ***' # dbg
1337 1337 # input history
1338 1338 self.savehist()
1339 1339
1340 1340 # Cleanup all tempfiles left around
1341 1341 for tfile in self.tempfiles:
1342 1342 try:
1343 1343 os.unlink(tfile)
1344 1344 except OSError:
1345 1345 pass
1346 1346
1347 1347 # Clear all user namespaces to release all references cleanly.
1348 1348 self.reset()
1349 1349
1350 1350 # Run user hooks
1351 1351 self.hooks.shutdown_hook()
1352 1352
1353 1353 def reset(self):
1354 1354 """Clear all internal namespaces.
1355 1355
1356 1356 Note that this is much more aggressive than %reset, since it clears
1357 1357 fully all namespaces, as well as all input/output lists.
1358 1358 """
1359 1359 for ns in self.ns_refs_table:
1360 1360 ns.clear()
1361 1361
1362 1362 # Clear input and output histories
1363 1363 self.input_hist[:] = []
1364 1364 self.input_hist_raw[:] = []
1365 1365 self.output_hist.clear()
1366 1366 # Restore the user namespaces to minimal usability
1367 1367 self.init_namespaces()
1368 1368
1369 1369 def savehist(self):
1370 1370 """Save input history to a file (via readline library)."""
1371 1371
1372 1372 if not self.has_readline:
1373 1373 return
1374 1374
1375 1375 try:
1376 1376 self.readline.write_history_file(self.histfile)
1377 1377 except:
1378 1378 print 'Unable to save IPython command history to file: ' + \
1379 1379 `self.histfile`
1380 1380
1381 1381 def reloadhist(self):
1382 1382 """Reload the input history from disk file."""
1383 1383
1384 1384 if self.has_readline:
1385 1385 try:
1386 1386 self.readline.clear_history()
1387 1387 self.readline.read_history_file(self.shell.histfile)
1388 1388 except AttributeError:
1389 1389 pass
1390 1390
1391 1391
1392 1392 def history_saving_wrapper(self, func):
1393 1393 """ Wrap func for readline history saving
1394 1394
1395 1395 Convert func into callable that saves & restores
1396 1396 history around the call """
1397 1397
1398 1398 if not self.has_readline:
1399 1399 return func
1400 1400
1401 1401 def wrapper():
1402 1402 self.savehist()
1403 1403 try:
1404 1404 func()
1405 1405 finally:
1406 1406 readline.read_history_file(self.histfile)
1407 1407 return wrapper
1408 1408
1409 1409 def pre_readline(self):
1410 1410 """readline hook to be used at the start of each line.
1411 1411
1412 1412 Currently it handles auto-indent only."""
1413 1413
1414 1414 #debugx('self.indent_current_nsp','pre_readline:')
1415 1415
1416 1416 if self.rl_do_indent:
1417 1417 self.readline.insert_text(self.indent_current_str())
1418 1418 if self.rl_next_input is not None:
1419 1419 self.readline.insert_text(self.rl_next_input)
1420 1420 self.rl_next_input = None
1421 1421
1422 1422 def init_readline(self):
1423 1423 """Command history completion/saving/reloading."""
1424 1424
1425 1425
1426 1426 import IPython.rlineimpl as readline
1427 1427
1428 1428 if not readline.have_readline:
1429 1429 self.has_readline = 0
1430 1430 self.readline = None
1431 1431 # no point in bugging windows users with this every time:
1432 1432 warn('Readline services not available on this platform.')
1433 1433 else:
1434 1434 sys.modules['readline'] = readline
1435 1435 import atexit
1436 1436 from IPython.completer import IPCompleter
1437 1437 self.Completer = IPCompleter(self,
1438 1438 self.user_ns,
1439 1439 self.user_global_ns,
1440 1440 self.rc.readline_omit__names,
1441 1441 self.alias_table)
1442 1442 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1443 1443 self.strdispatchers['complete_command'] = sdisp
1444 1444 self.Completer.custom_completers = sdisp
1445 1445 # Platform-specific configuration
1446 1446 if os.name == 'nt':
1447 1447 self.readline_startup_hook = readline.set_pre_input_hook
1448 1448 else:
1449 1449 self.readline_startup_hook = readline.set_startup_hook
1450 1450
1451 1451 # Load user's initrc file (readline config)
1452 1452 # Or if libedit is used, load editrc.
1453 1453 inputrc_name = os.environ.get('INPUTRC')
1454 1454 if inputrc_name is None:
1455 1455 home_dir = get_home_dir()
1456 1456 if home_dir is not None:
1457 1457 inputrc_name = '.inputrc'
1458 1458 if readline.uses_libedit:
1459 1459 inputrc_name = '.editrc'
1460 1460 inputrc_name = os.path.join(home_dir, inputrc_name)
1461 1461 if os.path.isfile(inputrc_name):
1462 1462 try:
1463 1463 readline.read_init_file(inputrc_name)
1464 1464 except:
1465 1465 warn('Problems reading readline initialization file <%s>'
1466 1466 % inputrc_name)
1467 1467
1468 1468 self.has_readline = 1
1469 1469 self.readline = readline
1470 1470 # save this in sys so embedded copies can restore it properly
1471 1471 sys.ipcompleter = self.Completer.complete
1472 1472 self.set_completer()
1473 1473
1474 1474 # Configure readline according to user's prefs
1475 1475 # This is only done if GNU readline is being used. If libedit
1476 1476 # is being used (as on Leopard) the readline config is
1477 1477 # not run as the syntax for libedit is different.
1478 1478 if not readline.uses_libedit:
1479 1479 for rlcommand in self.rc.readline_parse_and_bind:
1480 1480 #print "loading rl:",rlcommand # dbg
1481 1481 readline.parse_and_bind(rlcommand)
1482 1482
1483 1483 # Remove some chars from the delimiters list. If we encounter
1484 1484 # unicode chars, discard them.
1485 1485 delims = readline.get_completer_delims().encode("ascii", "ignore")
1486 1486 delims = delims.translate(string._idmap,
1487 1487 self.rc.readline_remove_delims)
1488 1488 readline.set_completer_delims(delims)
1489 1489 # otherwise we end up with a monster history after a while:
1490 1490 readline.set_history_length(1000)
1491 1491 try:
1492 1492 #print '*** Reading readline history' # dbg
1493 1493 readline.read_history_file(self.histfile)
1494 1494 except IOError:
1495 1495 pass # It doesn't exist yet.
1496 1496
1497 1497 atexit.register(self.atexit_operations)
1498 1498 del atexit
1499 1499
1500 1500 # Configure auto-indent for all platforms
1501 1501 self.set_autoindent(self.rc.autoindent)
1502 1502
1503 1503 def ask_yes_no(self,prompt,default=True):
1504 1504 if self.rc.quiet:
1505 1505 return True
1506 1506 return ask_yes_no(prompt,default)
1507 1507
1508 1508 def new_main_mod(self,ns=None):
1509 1509 """Return a new 'main' module object for user code execution.
1510 1510 """
1511 1511 main_mod = self._user_main_module
1512 1512 init_fakemod_dict(main_mod,ns)
1513 1513 return main_mod
1514 1514
1515 1515 def cache_main_mod(self,ns,fname):
1516 1516 """Cache a main module's namespace.
1517 1517
1518 1518 When scripts are executed via %run, we must keep a reference to the
1519 1519 namespace of their __main__ module (a FakeModule instance) around so
1520 1520 that Python doesn't clear it, rendering objects defined therein
1521 1521 useless.
1522 1522
1523 1523 This method keeps said reference in a private dict, keyed by the
1524 1524 absolute path of the module object (which corresponds to the script
1525 1525 path). This way, for multiple executions of the same script we only
1526 1526 keep one copy of the namespace (the last one), thus preventing memory
1527 1527 leaks from old references while allowing the objects from the last
1528 1528 execution to be accessible.
1529 1529
1530 1530 Note: we can not allow the actual FakeModule instances to be deleted,
1531 1531 because of how Python tears down modules (it hard-sets all their
1532 1532 references to None without regard for reference counts). This method
1533 1533 must therefore make a *copy* of the given namespace, to allow the
1534 1534 original module's __dict__ to be cleared and reused.
1535 1535
1536 1536
1537 1537 Parameters
1538 1538 ----------
1539 1539 ns : a namespace (a dict, typically)
1540 1540
1541 1541 fname : str
1542 1542 Filename associated with the namespace.
1543 1543
1544 1544 Examples
1545 1545 --------
1546 1546
1547 1547 In [10]: import IPython
1548 1548
1549 1549 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1550 1550
1551 1551 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1552 1552 Out[12]: True
1553 1553 """
1554 1554 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1555 1555
1556 1556 def clear_main_mod_cache(self):
1557 1557 """Clear the cache of main modules.
1558 1558
1559 1559 Mainly for use by utilities like %reset.
1560 1560
1561 1561 Examples
1562 1562 --------
1563 1563
1564 1564 In [15]: import IPython
1565 1565
1566 1566 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1567 1567
1568 1568 In [17]: len(_ip.IP._main_ns_cache) > 0
1569 1569 Out[17]: True
1570 1570
1571 1571 In [18]: _ip.IP.clear_main_mod_cache()
1572 1572
1573 1573 In [19]: len(_ip.IP._main_ns_cache) == 0
1574 1574 Out[19]: True
1575 1575 """
1576 1576 self._main_ns_cache.clear()
1577 1577
1578 1578 def _should_recompile(self,e):
1579 1579 """Utility routine for edit_syntax_error"""
1580 1580
1581 1581 if e.filename in ('<ipython console>','<input>','<string>',
1582 1582 '<console>','<BackgroundJob compilation>',
1583 1583 None):
1584 1584
1585 1585 return False
1586 1586 try:
1587 1587 if (self.rc.autoedit_syntax and
1588 1588 not self.ask_yes_no('Return to editor to correct syntax error? '
1589 1589 '[Y/n] ','y')):
1590 1590 return False
1591 1591 except EOFError:
1592 1592 return False
1593 1593
1594 1594 def int0(x):
1595 1595 try:
1596 1596 return int(x)
1597 1597 except TypeError:
1598 1598 return 0
1599 1599 # always pass integer line and offset values to editor hook
1600 1600 try:
1601 1601 self.hooks.fix_error_editor(e.filename,
1602 1602 int0(e.lineno),int0(e.offset),e.msg)
1603 1603 except IPython.ipapi.TryNext:
1604 1604 warn('Could not open editor')
1605 1605 return False
1606 1606 return True
1607 1607
1608 1608 def edit_syntax_error(self):
1609 1609 """The bottom half of the syntax error handler called in the main loop.
1610 1610
1611 1611 Loop until syntax error is fixed or user cancels.
1612 1612 """
1613 1613
1614 1614 while self.SyntaxTB.last_syntax_error:
1615 1615 # copy and clear last_syntax_error
1616 1616 err = self.SyntaxTB.clear_err_state()
1617 1617 if not self._should_recompile(err):
1618 1618 return
1619 1619 try:
1620 1620 # may set last_syntax_error again if a SyntaxError is raised
1621 1621 self.safe_execfile(err.filename,self.user_ns)
1622 1622 except:
1623 1623 self.showtraceback()
1624 1624 else:
1625 1625 try:
1626 1626 f = file(err.filename)
1627 1627 try:
1628 1628 sys.displayhook(f.read())
1629 1629 finally:
1630 1630 f.close()
1631 1631 except:
1632 1632 self.showtraceback()
1633 1633
1634 1634 def showsyntaxerror(self, filename=None):
1635 1635 """Display the syntax error that just occurred.
1636 1636
1637 1637 This doesn't display a stack trace because there isn't one.
1638 1638
1639 1639 If a filename is given, it is stuffed in the exception instead
1640 1640 of what was there before (because Python's parser always uses
1641 1641 "<string>" when reading from a string).
1642 1642 """
1643 1643 etype, value, last_traceback = sys.exc_info()
1644 1644
1645 1645 # See note about these variables in showtraceback() below
1646 1646 sys.last_type = etype
1647 1647 sys.last_value = value
1648 1648 sys.last_traceback = last_traceback
1649 1649
1650 1650 if filename and etype is SyntaxError:
1651 1651 # Work hard to stuff the correct filename in the exception
1652 1652 try:
1653 1653 msg, (dummy_filename, lineno, offset, line) = value
1654 1654 except:
1655 1655 # Not the format we expect; leave it alone
1656 1656 pass
1657 1657 else:
1658 1658 # Stuff in the right filename
1659 1659 try:
1660 1660 # Assume SyntaxError is a class exception
1661 1661 value = SyntaxError(msg, (filename, lineno, offset, line))
1662 1662 except:
1663 1663 # If that failed, assume SyntaxError is a string
1664 1664 value = msg, (filename, lineno, offset, line)
1665 1665 self.SyntaxTB(etype,value,[])
1666 1666
1667 1667 def debugger(self,force=False):
1668 1668 """Call the pydb/pdb debugger.
1669 1669
1670 1670 Keywords:
1671 1671
1672 1672 - force(False): by default, this routine checks the instance call_pdb
1673 1673 flag and does not actually invoke the debugger if the flag is false.
1674 1674 The 'force' option forces the debugger to activate even if the flag
1675 1675 is false.
1676 1676 """
1677 1677
1678 1678 if not (force or self.call_pdb):
1679 1679 return
1680 1680
1681 1681 if not hasattr(sys,'last_traceback'):
1682 1682 error('No traceback has been produced, nothing to debug.')
1683 1683 return
1684 1684
1685 1685 # use pydb if available
1686 1686 if Debugger.has_pydb:
1687 1687 from pydb import pm
1688 1688 else:
1689 1689 # fallback to our internal debugger
1690 1690 pm = lambda : self.InteractiveTB.debugger(force=True)
1691 1691 self.history_saving_wrapper(pm)()
1692 1692
1693 1693 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1694 1694 """Display the exception that just occurred.
1695 1695
1696 1696 If nothing is known about the exception, this is the method which
1697 1697 should be used throughout the code for presenting user tracebacks,
1698 1698 rather than directly invoking the InteractiveTB object.
1699 1699
1700 1700 A specific showsyntaxerror() also exists, but this method can take
1701 1701 care of calling it if needed, so unless you are explicitly catching a
1702 1702 SyntaxError exception, don't try to analyze the stack manually and
1703 1703 simply call this method."""
1704 1704
1705 1705
1706 1706 # Though this won't be called by syntax errors in the input line,
1707 1707 # there may be SyntaxError cases whith imported code.
1708 1708
1709 1709 try:
1710 1710 if exc_tuple is None:
1711 1711 etype, value, tb = sys.exc_info()
1712 1712 else:
1713 1713 etype, value, tb = exc_tuple
1714 1714
1715 1715 if etype is SyntaxError:
1716 1716 self.showsyntaxerror(filename)
1717 1717 elif etype is IPython.ipapi.UsageError:
1718 1718 print "UsageError:", value
1719 1719 else:
1720 1720 # WARNING: these variables are somewhat deprecated and not
1721 1721 # necessarily safe to use in a threaded environment, but tools
1722 1722 # like pdb depend on their existence, so let's set them. If we
1723 1723 # find problems in the field, we'll need to revisit their use.
1724 1724 sys.last_type = etype
1725 1725 sys.last_value = value
1726 1726 sys.last_traceback = tb
1727 1727
1728 1728 if etype in self.custom_exceptions:
1729 1729 self.CustomTB(etype,value,tb)
1730 1730 else:
1731 1731 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1732 1732 if self.InteractiveTB.call_pdb and self.has_readline:
1733 1733 # pdb mucks up readline, fix it back
1734 1734 self.set_completer()
1735 1735 except KeyboardInterrupt:
1736 1736 self.write("\nKeyboardInterrupt\n")
1737 1737
1738 1738 def mainloop(self,banner=None):
1739 1739 """Creates the local namespace and starts the mainloop.
1740 1740
1741 1741 If an optional banner argument is given, it will override the
1742 1742 internally created default banner."""
1743 1743
1744 1744 if self.rc.c: # Emulate Python's -c option
1745 1745 self.exec_init_cmd()
1746 1746 if banner is None:
1747 1747 if not self.rc.banner:
1748 1748 banner = ''
1749 1749 # banner is string? Use it directly!
1750 1750 elif isinstance(self.rc.banner,basestring):
1751 1751 banner = self.rc.banner
1752 1752 else:
1753 1753 banner = self.BANNER+self.banner2
1754 1754
1755 1755 # if you run stuff with -c <cmd>, raw hist is not updated
1756 1756 # ensure that it's in sync
1757 1757 if len(self.input_hist) != len (self.input_hist_raw):
1758 1758 self.input_hist_raw = InputList(self.input_hist)
1759 1759
1760 1760 while 1:
1761 1761 try:
1762 1762 self.interact(banner)
1763 1763 #self.interact_with_readline()
1764 1764
1765 1765 # XXX for testing of a readline-decoupled repl loop, call
1766 1766 # interact_with_readline above
1767 1767
1768 1768 break
1769 1769 except KeyboardInterrupt:
1770 1770 # this should not be necessary, but KeyboardInterrupt
1771 1771 # handling seems rather unpredictable...
1772 1772 self.write("\nKeyboardInterrupt in interact()\n")
1773 1773
1774 1774 def exec_init_cmd(self):
1775 1775 """Execute a command given at the command line.
1776 1776
1777 1777 This emulates Python's -c option."""
1778 1778
1779 1779 #sys.argv = ['-c']
1780 1780 self.push(self.prefilter(self.rc.c, False))
1781 1781 if not self.rc.interact:
1782 1782 self.ask_exit()
1783 1783
1784 1784 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1785 1785 """Embeds IPython into a running python program.
1786 1786
1787 1787 Input:
1788 1788
1789 1789 - header: An optional header message can be specified.
1790 1790
1791 1791 - local_ns, global_ns: working namespaces. If given as None, the
1792 1792 IPython-initialized one is updated with __main__.__dict__, so that
1793 1793 program variables become visible but user-specific configuration
1794 1794 remains possible.
1795 1795
1796 1796 - stack_depth: specifies how many levels in the stack to go to
1797 1797 looking for namespaces (when local_ns and global_ns are None). This
1798 1798 allows an intermediate caller to make sure that this function gets
1799 1799 the namespace from the intended level in the stack. By default (0)
1800 1800 it will get its locals and globals from the immediate caller.
1801 1801
1802 1802 Warning: it's possible to use this in a program which is being run by
1803 1803 IPython itself (via %run), but some funny things will happen (a few
1804 1804 globals get overwritten). In the future this will be cleaned up, as
1805 1805 there is no fundamental reason why it can't work perfectly."""
1806 1806
1807 1807 # Get locals and globals from caller
1808 1808 if local_ns is None or global_ns is None:
1809 1809 call_frame = sys._getframe(stack_depth).f_back
1810 1810
1811 1811 if local_ns is None:
1812 1812 local_ns = call_frame.f_locals
1813 1813 if global_ns is None:
1814 1814 global_ns = call_frame.f_globals
1815 1815
1816 1816 # Update namespaces and fire up interpreter
1817 1817
1818 1818 # The global one is easy, we can just throw it in
1819 1819 self.user_global_ns = global_ns
1820 1820
1821 1821 # but the user/local one is tricky: ipython needs it to store internal
1822 1822 # data, but we also need the locals. We'll copy locals in the user
1823 1823 # one, but will track what got copied so we can delete them at exit.
1824 1824 # This is so that a later embedded call doesn't see locals from a
1825 1825 # previous call (which most likely existed in a separate scope).
1826 1826 local_varnames = local_ns.keys()
1827 1827 self.user_ns.update(local_ns)
1828 1828 #self.user_ns['local_ns'] = local_ns # dbg
1829 1829
1830 1830 # Patch for global embedding to make sure that things don't overwrite
1831 1831 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1832 1832 # FIXME. Test this a bit more carefully (the if.. is new)
1833 1833 if local_ns is None and global_ns is None:
1834 1834 self.user_global_ns.update(__main__.__dict__)
1835 1835
1836 1836 # make sure the tab-completer has the correct frame information, so it
1837 1837 # actually completes using the frame's locals/globals
1838 1838 self.set_completer_frame()
1839 1839
1840 1840 # before activating the interactive mode, we need to make sure that
1841 1841 # all names in the builtin namespace needed by ipython point to
1842 1842 # ourselves, and not to other instances.
1843 1843 self.add_builtins()
1844 1844
1845 1845 self.interact(header)
1846 1846
1847 1847 # now, purge out the user namespace from anything we might have added
1848 1848 # from the caller's local namespace
1849 1849 delvar = self.user_ns.pop
1850 1850 for var in local_varnames:
1851 1851 delvar(var,None)
1852 1852 # and clean builtins we may have overridden
1853 1853 self.clean_builtins()
1854 1854
1855 1855 def interact_prompt(self):
1856 1856 """ Print the prompt (in read-eval-print loop)
1857 1857
1858 1858 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1859 1859 used in standard IPython flow.
1860 1860 """
1861 1861 if self.more:
1862 1862 try:
1863 1863 prompt = self.hooks.generate_prompt(True)
1864 1864 except:
1865 1865 self.showtraceback()
1866 1866 if self.autoindent:
1867 1867 self.rl_do_indent = True
1868 1868
1869 1869 else:
1870 1870 try:
1871 1871 prompt = self.hooks.generate_prompt(False)
1872 1872 except:
1873 1873 self.showtraceback()
1874 1874 self.write(prompt)
1875 1875
1876 1876 def interact_handle_input(self,line):
1877 1877 """ Handle the input line (in read-eval-print loop)
1878 1878
1879 1879 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1880 1880 used in standard IPython flow.
1881 1881 """
1882 1882 if line.lstrip() == line:
1883 1883 self.shadowhist.add(line.strip())
1884 1884 lineout = self.prefilter(line,self.more)
1885 1885
1886 1886 if line.strip():
1887 1887 if self.more:
1888 1888 self.input_hist_raw[-1] += '%s\n' % line
1889 1889 else:
1890 1890 self.input_hist_raw.append('%s\n' % line)
1891 1891
1892 1892
1893 1893 self.more = self.push(lineout)
1894 1894 if (self.SyntaxTB.last_syntax_error and
1895 1895 self.rc.autoedit_syntax):
1896 1896 self.edit_syntax_error()
1897 1897
1898 1898 def interact_with_readline(self):
1899 1899 """ Demo of using interact_handle_input, interact_prompt
1900 1900
1901 1901 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1902 1902 it should work like this.
1903 1903 """
1904 1904 self.readline_startup_hook(self.pre_readline)
1905 1905 while not self.exit_now:
1906 1906 self.interact_prompt()
1907 1907 if self.more:
1908 1908 self.rl_do_indent = True
1909 1909 else:
1910 1910 self.rl_do_indent = False
1911 1911 line = raw_input_original().decode(self.stdin_encoding)
1912 1912 self.interact_handle_input(line)
1913 1913
1914 1914
1915 1915 def interact(self, banner=None):
1916 1916 """Closely emulate the interactive Python console.
1917 1917
1918 1918 The optional banner argument specify the banner to print
1919 1919 before the first interaction; by default it prints a banner
1920 1920 similar to the one printed by the real Python interpreter,
1921 1921 followed by the current class name in parentheses (so as not
1922 1922 to confuse this with the real interpreter -- since it's so
1923 1923 close!).
1924 1924
1925 1925 """
1926 1926
1927 1927 if self.exit_now:
1928 1928 # batch run -> do not interact
1929 1929 return
1930 1930 cprt = 'Type "copyright", "credits" or "license" for more information.'
1931 1931 if banner is None:
1932 1932 self.write("Python %s on %s\n%s\n(%s)\n" %
1933 1933 (sys.version, sys.platform, cprt,
1934 1934 self.__class__.__name__))
1935 1935 else:
1936 1936 self.write(banner)
1937 1937
1938 1938 more = 0
1939 1939
1940 1940 # Mark activity in the builtins
1941 1941 __builtin__.__dict__['__IPYTHON__active'] += 1
1942 1942
1943 1943 if self.has_readline:
1944 1944 self.readline_startup_hook(self.pre_readline)
1945 1945 # exit_now is set by a call to %Exit or %Quit, through the
1946 1946 # ask_exit callback.
1947 1947
1948 1948 while not self.exit_now:
1949 1949 self.hooks.pre_prompt_hook()
1950 1950 if more:
1951 1951 try:
1952 1952 prompt = self.hooks.generate_prompt(True)
1953 1953 except:
1954 1954 self.showtraceback()
1955 1955 if self.autoindent:
1956 1956 self.rl_do_indent = True
1957 1957
1958 1958 else:
1959 1959 try:
1960 1960 prompt = self.hooks.generate_prompt(False)
1961 1961 except:
1962 1962 self.showtraceback()
1963 1963 try:
1964 1964 line = self.raw_input(prompt,more)
1965 1965 if self.exit_now:
1966 1966 # quick exit on sys.std[in|out] close
1967 1967 break
1968 1968 if self.autoindent:
1969 1969 self.rl_do_indent = False
1970 1970
1971 1971 except KeyboardInterrupt:
1972 1972 #double-guard against keyboardinterrupts during kbdint handling
1973 1973 try:
1974 1974 self.write('\nKeyboardInterrupt\n')
1975 1975 self.resetbuffer()
1976 1976 # keep cache in sync with the prompt counter:
1977 1977 self.outputcache.prompt_count -= 1
1978 1978
1979 1979 if self.autoindent:
1980 1980 self.indent_current_nsp = 0
1981 1981 more = 0
1982 1982 except KeyboardInterrupt:
1983 1983 pass
1984 1984 except EOFError:
1985 1985 if self.autoindent:
1986 1986 self.rl_do_indent = False
1987 1987 if self.has_readline:
1988 1988 self.readline_startup_hook(None)
1989 1989 self.write('\n')
1990 1990 self.exit()
1991 1991 except bdb.BdbQuit:
1992 1992 warn('The Python debugger has exited with a BdbQuit exception.\n'
1993 1993 'Because of how pdb handles the stack, it is impossible\n'
1994 1994 'for IPython to properly format this particular exception.\n'
1995 1995 'IPython will resume normal operation.')
1996 1996 except:
1997 1997 # exceptions here are VERY RARE, but they can be triggered
1998 1998 # asynchronously by signal handlers, for example.
1999 1999 self.showtraceback()
2000 2000 else:
2001 2001 more = self.push(line)
2002 2002 if (self.SyntaxTB.last_syntax_error and
2003 2003 self.rc.autoedit_syntax):
2004 2004 self.edit_syntax_error()
2005 2005
2006 2006 # We are off again...
2007 2007 __builtin__.__dict__['__IPYTHON__active'] -= 1
2008 2008
2009 2009 def excepthook(self, etype, value, tb):
2010 2010 """One more defense for GUI apps that call sys.excepthook.
2011 2011
2012 2012 GUI frameworks like wxPython trap exceptions and call
2013 2013 sys.excepthook themselves. I guess this is a feature that
2014 2014 enables them to keep running after exceptions that would
2015 2015 otherwise kill their mainloop. This is a bother for IPython
2016 2016 which excepts to catch all of the program exceptions with a try:
2017 2017 except: statement.
2018 2018
2019 2019 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
2020 2020 any app directly invokes sys.excepthook, it will look to the user like
2021 2021 IPython crashed. In order to work around this, we can disable the
2022 2022 CrashHandler and replace it with this excepthook instead, which prints a
2023 2023 regular traceback using our InteractiveTB. In this fashion, apps which
2024 2024 call sys.excepthook will generate a regular-looking exception from
2025 2025 IPython, and the CrashHandler will only be triggered by real IPython
2026 2026 crashes.
2027 2027
2028 2028 This hook should be used sparingly, only in places which are not likely
2029 2029 to be true IPython errors.
2030 2030 """
2031 2031 self.showtraceback((etype,value,tb),tb_offset=0)
2032 2032
2033 2033 def expand_aliases(self,fn,rest):
2034 2034 """ Expand multiple levels of aliases:
2035 2035
2036 2036 if:
2037 2037
2038 2038 alias foo bar /tmp
2039 2039 alias baz foo
2040 2040
2041 2041 then:
2042 2042
2043 2043 baz huhhahhei -> bar /tmp huhhahhei
2044 2044
2045 2045 """
2046 2046 line = fn + " " + rest
2047 2047
2048 2048 done = set()
2049 2049 while 1:
2050 2050 pre,fn,rest = prefilter.splitUserInput(line,
2051 2051 prefilter.shell_line_split)
2052 2052 if fn in self.alias_table:
2053 2053 if fn in done:
2054 2054 warn("Cyclic alias definition, repeated '%s'" % fn)
2055 2055 return ""
2056 2056 done.add(fn)
2057 2057
2058 2058 l2 = self.transform_alias(fn,rest)
2059 2059 # dir -> dir
2060 2060 # print "alias",line, "->",l2 #dbg
2061 2061 if l2 == line:
2062 2062 break
2063 2063 # ls -> ls -F should not recurse forever
2064 2064 if l2.split(None,1)[0] == line.split(None,1)[0]:
2065 2065 line = l2
2066 2066 break
2067 2067
2068 2068 line=l2
2069 2069
2070 2070
2071 2071 # print "al expand to",line #dbg
2072 2072 else:
2073 2073 break
2074 2074
2075 2075 return line
2076 2076
2077 2077 def transform_alias(self, alias,rest=''):
2078 2078 """ Transform alias to system command string.
2079 2079 """
2080 2080 trg = self.alias_table[alias]
2081 2081
2082 2082 nargs,cmd = trg
2083 2083 # print trg #dbg
2084 2084 if ' ' in cmd and os.path.isfile(cmd):
2085 2085 cmd = '"%s"' % cmd
2086 2086
2087 2087 # Expand the %l special to be the user's input line
2088 2088 if cmd.find('%l') >= 0:
2089 2089 cmd = cmd.replace('%l',rest)
2090 2090 rest = ''
2091 2091 if nargs==0:
2092 2092 # Simple, argument-less aliases
2093 2093 cmd = '%s %s' % (cmd,rest)
2094 2094 else:
2095 2095 # Handle aliases with positional arguments
2096 2096 args = rest.split(None,nargs)
2097 2097 if len(args)< nargs:
2098 2098 error('Alias <%s> requires %s arguments, %s given.' %
2099 2099 (alias,nargs,len(args)))
2100 2100 return None
2101 2101 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2102 2102 # Now call the macro, evaluating in the user's namespace
2103 2103 #print 'new command: <%r>' % cmd # dbg
2104 2104 return cmd
2105 2105
2106 2106 def call_alias(self,alias,rest=''):
2107 2107 """Call an alias given its name and the rest of the line.
2108 2108
2109 2109 This is only used to provide backwards compatibility for users of
2110 2110 ipalias(), use of which is not recommended for anymore."""
2111 2111
2112 2112 # Now call the macro, evaluating in the user's namespace
2113 2113 cmd = self.transform_alias(alias, rest)
2114 2114 try:
2115 2115 self.system(cmd)
2116 2116 except:
2117 2117 self.showtraceback()
2118 2118
2119 2119 def indent_current_str(self):
2120 2120 """return the current level of indentation as a string"""
2121 2121 return self.indent_current_nsp * ' '
2122 2122
2123 2123 def autoindent_update(self,line):
2124 2124 """Keep track of the indent level."""
2125 2125
2126 2126 #debugx('line')
2127 2127 #debugx('self.indent_current_nsp')
2128 2128 if self.autoindent:
2129 2129 if line:
2130 2130 inisp = num_ini_spaces(line)
2131 2131 if inisp < self.indent_current_nsp:
2132 2132 self.indent_current_nsp = inisp
2133 2133
2134 2134 if line[-1] == ':':
2135 2135 self.indent_current_nsp += 4
2136 2136 elif dedent_re.match(line):
2137 2137 self.indent_current_nsp -= 4
2138 2138 else:
2139 2139 self.indent_current_nsp = 0
2140 2140
2141 2141 def runlines(self,lines):
2142 2142 """Run a string of one or more lines of source.
2143 2143
2144 2144 This method is capable of running a string containing multiple source
2145 2145 lines, as if they had been entered at the IPython prompt. Since it
2146 2146 exposes IPython's processing machinery, the given strings can contain
2147 2147 magic calls (%magic), special shell access (!cmd), etc."""
2148 2148
2149 2149 # We must start with a clean buffer, in case this is run from an
2150 2150 # interactive IPython session (via a magic, for example).
2151 2151 self.resetbuffer()
2152 2152 lines = lines.split('\n')
2153 2153 more = 0
2154 2154
2155 2155 for line in lines:
2156 2156 # skip blank lines so we don't mess up the prompt counter, but do
2157 2157 # NOT skip even a blank line if we are in a code block (more is
2158 2158 # true)
2159 2159
2160 2160 if line or more:
2161 2161 # push to raw history, so hist line numbers stay in sync
2162 2162 self.input_hist_raw.append("# " + line + "\n")
2163 2163 more = self.push(self.prefilter(line,more))
2164 2164 # IPython's runsource returns None if there was an error
2165 2165 # compiling the code. This allows us to stop processing right
2166 2166 # away, so the user gets the error message at the right place.
2167 2167 if more is None:
2168 2168 break
2169 2169 else:
2170 2170 self.input_hist_raw.append("\n")
2171 2171 # final newline in case the input didn't have it, so that the code
2172 2172 # actually does get executed
2173 2173 if more:
2174 2174 self.push('\n')
2175 2175
2176 2176 def runsource(self, source, filename='<input>', symbol='single'):
2177 2177 """Compile and run some source in the interpreter.
2178 2178
2179 2179 Arguments are as for compile_command().
2180 2180
2181 2181 One several things can happen:
2182 2182
2183 2183 1) The input is incorrect; compile_command() raised an
2184 2184 exception (SyntaxError or OverflowError). A syntax traceback
2185 2185 will be printed by calling the showsyntaxerror() method.
2186 2186
2187 2187 2) The input is incomplete, and more input is required;
2188 2188 compile_command() returned None. Nothing happens.
2189 2189
2190 2190 3) The input is complete; compile_command() returned a code
2191 2191 object. The code is executed by calling self.runcode() (which
2192 2192 also handles run-time exceptions, except for SystemExit).
2193 2193
2194 2194 The return value is:
2195 2195
2196 2196 - True in case 2
2197 2197
2198 2198 - False in the other cases, unless an exception is raised, where
2199 2199 None is returned instead. This can be used by external callers to
2200 2200 know whether to continue feeding input or not.
2201 2201
2202 2202 The return value can be used to decide whether to use sys.ps1 or
2203 2203 sys.ps2 to prompt the next line."""
2204 2204
2205 2205 # if the source code has leading blanks, add 'if 1:\n' to it
2206 2206 # this allows execution of indented pasted code. It is tempting
2207 2207 # to add '\n' at the end of source to run commands like ' a=1'
2208 2208 # directly, but this fails for more complicated scenarios
2209 2209 source=source.encode(self.stdin_encoding)
2210 2210 if source[:1] in [' ', '\t']:
2211 2211 source = 'if 1:\n%s' % source
2212 2212
2213 2213 try:
2214 2214 code = self.compile(source,filename,symbol)
2215 2215 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2216 2216 # Case 1
2217 2217 self.showsyntaxerror(filename)
2218 2218 return None
2219 2219
2220 2220 if code is None:
2221 2221 # Case 2
2222 2222 return True
2223 2223
2224 2224 # Case 3
2225 2225 # We store the code object so that threaded shells and
2226 2226 # custom exception handlers can access all this info if needed.
2227 2227 # The source corresponding to this can be obtained from the
2228 2228 # buffer attribute as '\n'.join(self.buffer).
2229 2229 self.code_to_run = code
2230 2230 # now actually execute the code object
2231 2231 if self.runcode(code) == 0:
2232 2232 return False
2233 2233 else:
2234 2234 return None
2235 2235
2236 2236 def runcode(self,code_obj):
2237 2237 """Execute a code object.
2238 2238
2239 2239 When an exception occurs, self.showtraceback() is called to display a
2240 2240 traceback.
2241 2241
2242 2242 Return value: a flag indicating whether the code to be run completed
2243 2243 successfully:
2244 2244
2245 2245 - 0: successful execution.
2246 2246 - 1: an error occurred.
2247 2247 """
2248 2248
2249 2249 # Set our own excepthook in case the user code tries to call it
2250 2250 # directly, so that the IPython crash handler doesn't get triggered
2251 2251 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2252 2252
2253 2253 # we save the original sys.excepthook in the instance, in case config
2254 2254 # code (such as magics) needs access to it.
2255 2255 self.sys_excepthook = old_excepthook
2256 2256 outflag = 1 # happens in more places, so it's easier as default
2257 2257 try:
2258 2258 try:
2259 2259 self.hooks.pre_runcode_hook()
2260 2260 exec code_obj in self.user_global_ns, self.user_ns
2261 2261 finally:
2262 2262 # Reset our crash handler in place
2263 2263 sys.excepthook = old_excepthook
2264 2264 except SystemExit:
2265 2265 self.resetbuffer()
2266 2266 self.showtraceback()
2267 2267 warn("Type %exit or %quit to exit IPython "
2268 2268 "(%Exit or %Quit do so unconditionally).",level=1)
2269 2269 except self.custom_exceptions:
2270 2270 etype,value,tb = sys.exc_info()
2271 2271 self.CustomTB(etype,value,tb)
2272 2272 except:
2273 2273 self.showtraceback()
2274 2274 else:
2275 2275 outflag = 0
2276 2276 if softspace(sys.stdout, 0):
2277 2277 print
2278 2278 # Flush out code object which has been run (and source)
2279 2279 self.code_to_run = None
2280 2280 return outflag
2281 2281
2282 2282 def push(self, line):
2283 2283 """Push a line to the interpreter.
2284 2284
2285 2285 The line should not have a trailing newline; it may have
2286 2286 internal newlines. The line is appended to a buffer and the
2287 2287 interpreter's runsource() method is called with the
2288 2288 concatenated contents of the buffer as source. If this
2289 2289 indicates that the command was executed or invalid, the buffer
2290 2290 is reset; otherwise, the command is incomplete, and the buffer
2291 2291 is left as it was after the line was appended. The return
2292 2292 value is 1 if more input is required, 0 if the line was dealt
2293 2293 with in some way (this is the same as runsource()).
2294 2294 """
2295 2295
2296 2296 # autoindent management should be done here, and not in the
2297 2297 # interactive loop, since that one is only seen by keyboard input. We
2298 2298 # need this done correctly even for code run via runlines (which uses
2299 2299 # push).
2300 2300
2301 2301 #print 'push line: <%s>' % line # dbg
2302 2302 for subline in line.splitlines():
2303 2303 self.autoindent_update(subline)
2304 2304 self.buffer.append(line)
2305 2305 more = self.runsource('\n'.join(self.buffer), self.filename)
2306 2306 if not more:
2307 2307 self.resetbuffer()
2308 2308 return more
2309 2309
2310 2310 def split_user_input(self, line):
2311 2311 # This is really a hold-over to support ipapi and some extensions
2312 2312 return prefilter.splitUserInput(line)
2313 2313
2314 2314 def resetbuffer(self):
2315 2315 """Reset the input buffer."""
2316 2316 self.buffer[:] = []
2317 2317
2318 2318 def raw_input(self,prompt='',continue_prompt=False):
2319 2319 """Write a prompt and read a line.
2320 2320
2321 2321 The returned line does not include the trailing newline.
2322 2322 When the user enters the EOF key sequence, EOFError is raised.
2323 2323
2324 2324 Optional inputs:
2325 2325
2326 2326 - prompt(''): a string to be printed to prompt the user.
2327 2327
2328 2328 - continue_prompt(False): whether this line is the first one or a
2329 2329 continuation in a sequence of inputs.
2330 2330 """
2331 2331
2332 2332 # Code run by the user may have modified the readline completer state.
2333 2333 # We must ensure that our completer is back in place.
2334 2334 if self.has_readline:
2335 2335 self.set_completer()
2336 2336
2337 2337 try:
2338 2338 line = raw_input_original(prompt).decode(self.stdin_encoding)
2339 2339 except ValueError:
2340 2340 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2341 2341 " or sys.stdout.close()!\nExiting IPython!")
2342 2342 self.ask_exit()
2343 2343 return ""
2344 2344
2345 2345 # Try to be reasonably smart about not re-indenting pasted input more
2346 2346 # than necessary. We do this by trimming out the auto-indent initial
2347 2347 # spaces, if the user's actual input started itself with whitespace.
2348 2348 #debugx('self.buffer[-1]')
2349 2349
2350 2350 if self.autoindent:
2351 2351 if num_ini_spaces(line) > self.indent_current_nsp:
2352 2352 line = line[self.indent_current_nsp:]
2353 2353 self.indent_current_nsp = 0
2354 2354
2355 2355 # store the unfiltered input before the user has any chance to modify
2356 2356 # it.
2357 2357 if line.strip():
2358 2358 if continue_prompt:
2359 2359 self.input_hist_raw[-1] += '%s\n' % line
2360 2360 if self.has_readline: # and some config option is set?
2361 2361 try:
2362 2362 histlen = self.readline.get_current_history_length()
2363 2363 if histlen > 1:
2364 2364 newhist = self.input_hist_raw[-1].rstrip()
2365 2365 self.readline.remove_history_item(histlen-1)
2366 2366 self.readline.replace_history_item(histlen-2,
2367 2367 newhist.encode(self.stdin_encoding))
2368 2368 except AttributeError:
2369 2369 pass # re{move,place}_history_item are new in 2.4.
2370 2370 else:
2371 2371 self.input_hist_raw.append('%s\n' % line)
2372 2372 # only entries starting at first column go to shadow history
2373 2373 if line.lstrip() == line:
2374 2374 self.shadowhist.add(line.strip())
2375 2375 elif not continue_prompt:
2376 2376 self.input_hist_raw.append('\n')
2377 2377 try:
2378 2378 lineout = self.prefilter(line,continue_prompt)
2379 2379 except:
2380 2380 # blanket except, in case a user-defined prefilter crashes, so it
2381 2381 # can't take all of ipython with it.
2382 2382 self.showtraceback()
2383 2383 return ''
2384 2384 else:
2385 2385 return lineout
2386 2386
2387 2387 def _prefilter(self, line, continue_prompt):
2388 2388 """Calls different preprocessors, depending on the form of line."""
2389 2389
2390 2390 # All handlers *must* return a value, even if it's blank ('').
2391 2391
2392 2392 # Lines are NOT logged here. Handlers should process the line as
2393 2393 # needed, update the cache AND log it (so that the input cache array
2394 2394 # stays synced).
2395 2395
2396 2396 #.....................................................................
2397 2397 # Code begins
2398 2398
2399 2399 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2400 2400
2401 2401 # save the line away in case we crash, so the post-mortem handler can
2402 2402 # record it
2403 2403 self._last_input_line = line
2404 2404
2405 2405 #print '***line: <%s>' % line # dbg
2406 2406
2407 2407 if not line:
2408 2408 # Return immediately on purely empty lines, so that if the user
2409 2409 # previously typed some whitespace that started a continuation
2410 2410 # prompt, he can break out of that loop with just an empty line.
2411 2411 # This is how the default python prompt works.
2412 2412
2413 2413 # Only return if the accumulated input buffer was just whitespace!
2414 2414 if ''.join(self.buffer).isspace():
2415 2415 self.buffer[:] = []
2416 2416 return ''
2417 2417
2418 2418 line_info = prefilter.LineInfo(line, continue_prompt)
2419 2419
2420 2420 # the input history needs to track even empty lines
2421 2421 stripped = line.strip()
2422 2422
2423 2423 if not stripped:
2424 2424 if not continue_prompt:
2425 2425 self.outputcache.prompt_count -= 1
2426 2426 return self.handle_normal(line_info)
2427 2427
2428 2428 # print '***cont',continue_prompt # dbg
2429 2429 # special handlers are only allowed for single line statements
2430 2430 if continue_prompt and not self.rc.multi_line_specials:
2431 2431 return self.handle_normal(line_info)
2432 2432
2433 2433
2434 2434 # See whether any pre-existing handler can take care of it
2435 2435 rewritten = self.hooks.input_prefilter(stripped)
2436 2436 if rewritten != stripped: # ok, some prefilter did something
2437 2437 rewritten = line_info.pre + rewritten # add indentation
2438 2438 return self.handle_normal(prefilter.LineInfo(rewritten,
2439 2439 continue_prompt))
2440 2440
2441 2441 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2442 2442
2443 2443 return prefilter.prefilter(line_info, self)
2444 2444
2445 2445
2446 2446 def _prefilter_dumb(self, line, continue_prompt):
2447 2447 """simple prefilter function, for debugging"""
2448 2448 return self.handle_normal(line,continue_prompt)
2449 2449
2450 2450
2451 2451 def multiline_prefilter(self, line, continue_prompt):
2452 2452 """ Run _prefilter for each line of input
2453 2453
2454 2454 Covers cases where there are multiple lines in the user entry,
2455 2455 which is the case when the user goes back to a multiline history
2456 2456 entry and presses enter.
2457 2457
2458 2458 """
2459 2459 out = []
2460 2460 for l in line.rstrip('\n').split('\n'):
2461 2461 out.append(self._prefilter(l, continue_prompt))
2462 2462 return '\n'.join(out)
2463 2463
2464 2464 # Set the default prefilter() function (this can be user-overridden)
2465 2465 prefilter = multiline_prefilter
2466 2466
2467 2467 def handle_normal(self,line_info):
2468 2468 """Handle normal input lines. Use as a template for handlers."""
2469 2469
2470 2470 # With autoindent on, we need some way to exit the input loop, and I
2471 2471 # don't want to force the user to have to backspace all the way to
2472 2472 # clear the line. The rule will be in this case, that either two
2473 2473 # lines of pure whitespace in a row, or a line of pure whitespace but
2474 2474 # of a size different to the indent level, will exit the input loop.
2475 2475 line = line_info.line
2476 2476 continue_prompt = line_info.continue_prompt
2477 2477
2478 2478 if (continue_prompt and self.autoindent and line.isspace() and
2479 2479 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2480 2480 (self.buffer[-1]).isspace() )):
2481 2481 line = ''
2482 2482
2483 2483 self.log(line,line,continue_prompt)
2484 2484 return line
2485 2485
2486 2486 def handle_alias(self,line_info):
2487 2487 """Handle alias input lines. """
2488 2488 tgt = self.alias_table[line_info.iFun]
2489 2489 # print "=>",tgt #dbg
2490 2490 if callable(tgt):
2491 2491 if '$' in line_info.line:
2492 2492 call_meth = '(_ip, _ip.itpl(%s))'
2493 2493 else:
2494 2494 call_meth = '(_ip,%s)'
2495 2495 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2496 2496 line_info.iFun,
2497 2497 make_quoted_expr(line_info.line))
2498 2498 else:
2499 2499 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2500 2500
2501 2501 # pre is needed, because it carries the leading whitespace. Otherwise
2502 2502 # aliases won't work in indented sections.
2503 2503 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2504 2504 make_quoted_expr( transformed ))
2505 2505
2506 2506 self.log(line_info.line,line_out,line_info.continue_prompt)
2507 2507 #print 'line out:',line_out # dbg
2508 2508 return line_out
2509 2509
2510 2510 def handle_shell_escape(self, line_info):
2511 2511 """Execute the line in a shell, empty return value"""
2512 2512 #print 'line in :', `line` # dbg
2513 2513 line = line_info.line
2514 2514 if line.lstrip().startswith('!!'):
2515 2515 # rewrite LineInfo's line, iFun and theRest to properly hold the
2516 2516 # call to %sx and the actual command to be executed, so
2517 2517 # handle_magic can work correctly. Note that this works even if
2518 2518 # the line is indented, so it handles multi_line_specials
2519 2519 # properly.
2520 2520 new_rest = line.lstrip()[2:]
2521 2521 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2522 2522 line_info.iFun = 'sx'
2523 2523 line_info.theRest = new_rest
2524 2524 return self.handle_magic(line_info)
2525 2525 else:
2526 2526 cmd = line.lstrip().lstrip('!')
2527 2527 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2528 2528 make_quoted_expr(cmd))
2529 2529 # update cache/log and return
2530 2530 self.log(line,line_out,line_info.continue_prompt)
2531 2531 return line_out
2532 2532
2533 2533 def handle_magic(self, line_info):
2534 2534 """Execute magic functions."""
2535 2535 iFun = line_info.iFun
2536 2536 theRest = line_info.theRest
2537 2537 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2538 2538 make_quoted_expr(iFun + " " + theRest))
2539 2539 self.log(line_info.line,cmd,line_info.continue_prompt)
2540 2540 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2541 2541 return cmd
2542 2542
2543 2543 def handle_auto(self, line_info):
2544 2544 """Hande lines which can be auto-executed, quoting if requested."""
2545 2545
2546 2546 line = line_info.line
2547 2547 iFun = line_info.iFun
2548 2548 theRest = line_info.theRest
2549 2549 pre = line_info.pre
2550 2550 continue_prompt = line_info.continue_prompt
2551 2551 obj = line_info.ofind(self)['obj']
2552 2552
2553 2553 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2554 2554
2555 2555 # This should only be active for single-line input!
2556 2556 if continue_prompt:
2557 2557 self.log(line,line,continue_prompt)
2558 2558 return line
2559 2559
2560 2560 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2561 2561 auto_rewrite = True
2562 2562
2563 2563 if pre == self.ESC_QUOTE:
2564 2564 # Auto-quote splitting on whitespace
2565 2565 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2566 2566 elif pre == self.ESC_QUOTE2:
2567 2567 # Auto-quote whole string
2568 2568 newcmd = '%s("%s")' % (iFun,theRest)
2569 2569 elif pre == self.ESC_PAREN:
2570 2570 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2571 2571 else:
2572 2572 # Auto-paren.
2573 2573 # We only apply it to argument-less calls if the autocall
2574 2574 # parameter is set to 2. We only need to check that autocall is <
2575 2575 # 2, since this function isn't called unless it's at least 1.
2576 2576 if not theRest and (self.rc.autocall < 2) and not force_auto:
2577 2577 newcmd = '%s %s' % (iFun,theRest)
2578 2578 auto_rewrite = False
2579 2579 else:
2580 2580 if not force_auto and theRest.startswith('['):
2581 2581 if hasattr(obj,'__getitem__'):
2582 2582 # Don't autocall in this case: item access for an object
2583 2583 # which is BOTH callable and implements __getitem__.
2584 2584 newcmd = '%s %s' % (iFun,theRest)
2585 2585 auto_rewrite = False
2586 2586 else:
2587 2587 # if the object doesn't support [] access, go ahead and
2588 2588 # autocall
2589 2589 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2590 2590 elif theRest.endswith(';'):
2591 2591 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2592 2592 else:
2593 2593 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2594 2594
2595 2595 if auto_rewrite:
2596 2596 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2597 2597
2598 2598 try:
2599 2599 # plain ascii works better w/ pyreadline, on some machines, so
2600 2600 # we use it and only print uncolored rewrite if we have unicode
2601 2601 rw = str(rw)
2602 2602 print >>Term.cout, rw
2603 2603 except UnicodeEncodeError:
2604 2604 print "-------------->" + newcmd
2605 2605
2606 2606 # log what is now valid Python, not the actual user input (without the
2607 2607 # final newline)
2608 2608 self.log(line,newcmd,continue_prompt)
2609 2609 return newcmd
2610 2610
2611 2611 def handle_help(self, line_info):
2612 2612 """Try to get some help for the object.
2613 2613
2614 2614 obj? or ?obj -> basic information.
2615 2615 obj?? or ??obj -> more details.
2616 2616 """
2617 2617
2618 2618 line = line_info.line
2619 2619 # We need to make sure that we don't process lines which would be
2620 2620 # otherwise valid python, such as "x=1 # what?"
2621 2621 try:
2622 2622 codeop.compile_command(line)
2623 2623 except SyntaxError:
2624 2624 # We should only handle as help stuff which is NOT valid syntax
2625 2625 if line[0]==self.ESC_HELP:
2626 2626 line = line[1:]
2627 2627 elif line[-1]==self.ESC_HELP:
2628 2628 line = line[:-1]
2629 2629 self.log(line,'#?'+line,line_info.continue_prompt)
2630 2630 if line:
2631 2631 #print 'line:<%r>' % line # dbg
2632 2632 self.magic_pinfo(line)
2633 2633 else:
2634 2634 page(self.usage,screen_lines=self.rc.screen_length)
2635 2635 return '' # Empty string is needed here!
2636 2636 except:
2637 2637 # Pass any other exceptions through to the normal handler
2638 2638 return self.handle_normal(line_info)
2639 2639 else:
2640 2640 # If the code compiles ok, we should handle it normally
2641 2641 return self.handle_normal(line_info)
2642 2642
2643 2643 def getapi(self):
2644 2644 """ Get an IPApi object for this shell instance
2645 2645
2646 2646 Getting an IPApi object is always preferable to accessing the shell
2647 2647 directly, but this holds true especially for extensions.
2648 2648
2649 2649 It should always be possible to implement an extension with IPApi
2650 2650 alone. If not, contact maintainer to request an addition.
2651 2651
2652 2652 """
2653 2653 return self.api
2654 2654
2655 2655 def handle_emacs(self, line_info):
2656 2656 """Handle input lines marked by python-mode."""
2657 2657
2658 2658 # Currently, nothing is done. Later more functionality can be added
2659 2659 # here if needed.
2660 2660
2661 2661 # The input cache shouldn't be updated
2662 2662 return line_info.line
2663 2663
2664 2664
2665 2665 def mktempfile(self,data=None):
2666 2666 """Make a new tempfile and return its filename.
2667 2667
2668 2668 This makes a call to tempfile.mktemp, but it registers the created
2669 2669 filename internally so ipython cleans it up at exit time.
2670 2670
2671 2671 Optional inputs:
2672 2672
2673 2673 - data(None): if data is given, it gets written out to the temp file
2674 2674 immediately, and the file is closed again."""
2675 2675
2676 2676 filename = tempfile.mktemp('.py','ipython_edit_')
2677 2677 self.tempfiles.append(filename)
2678 2678
2679 2679 if data:
2680 2680 tmp_file = open(filename,'w')
2681 2681 tmp_file.write(data)
2682 2682 tmp_file.close()
2683 2683 return filename
2684 2684
2685 2685 def write(self,data):
2686 2686 """Write a string to the default output"""
2687 2687 Term.cout.write(data)
2688 2688
2689 2689 def write_err(self,data):
2690 2690 """Write a string to the default error output"""
2691 2691 Term.cerr.write(data)
2692 2692
2693 2693 def ask_exit(self):
2694 2694 """ Call for exiting. Can be overiden and used as a callback. """
2695 2695 self.exit_now = True
2696 2696
2697 2697 def exit(self):
2698 2698 """Handle interactive exit.
2699 2699
2700 2700 This method calls the ask_exit callback."""
2701 2701
2702 2702 if self.rc.confirm_exit:
2703 2703 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2704 2704 self.ask_exit()
2705 2705 else:
2706 2706 self.ask_exit()
2707 2707
2708 2708 def safe_execfile(self,fname,*where,**kw):
2709 2709 """A safe version of the builtin execfile().
2710 2710
2711 2711 This version will never throw an exception, and knows how to handle
2712 2712 ipython logs as well.
2713 2713
2714 2714 :Parameters:
2715 2715 fname : string
2716 2716 Name of the file to be executed.
2717 2717
2718 2718 where : tuple
2719 2719 One or two namespaces, passed to execfile() as (globals,locals).
2720 2720 If only one is given, it is passed as both.
2721 2721
2722 2722 :Keywords:
2723 2723 islog : boolean (False)
2724 2724
2725 2725 quiet : boolean (True)
2726 2726
2727 2727 exit_ignore : boolean (False)
2728 2728 """
2729 2729
2730 2730 def syspath_cleanup():
2731 2731 """Internal cleanup routine for sys.path."""
2732 2732 if add_dname:
2733 2733 try:
2734 2734 sys.path.remove(dname)
2735 2735 except ValueError:
2736 2736 # For some reason the user has already removed it, ignore.
2737 2737 pass
2738 2738
2739 2739 fname = os.path.expanduser(fname)
2740 2740
2741 2741 # Find things also in current directory. This is needed to mimic the
2742 2742 # behavior of running a script from the system command line, where
2743 2743 # Python inserts the script's directory into sys.path
2744 2744 dname = os.path.dirname(os.path.abspath(fname))
2745 2745 add_dname = False
2746 2746 if dname not in sys.path:
2747 2747 sys.path.insert(0,dname)
2748 2748 add_dname = True
2749 2749
2750 2750 try:
2751 2751 xfile = open(fname)
2752 2752 except:
2753 2753 print >> Term.cerr, \
2754 2754 'Could not open file <%s> for safe execution.' % fname
2755 2755 syspath_cleanup()
2756 2756 return None
2757 2757
2758 2758 kw.setdefault('islog',0)
2759 2759 kw.setdefault('quiet',1)
2760 2760 kw.setdefault('exit_ignore',0)
2761 2761
2762 2762 first = xfile.readline()
2763 2763 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2764 2764 xfile.close()
2765 2765 # line by line execution
2766 2766 if first.startswith(loghead) or kw['islog']:
2767 2767 print 'Loading log file <%s> one line at a time...' % fname
2768 2768 if kw['quiet']:
2769 2769 stdout_save = sys.stdout
2770 2770 sys.stdout = StringIO.StringIO()
2771 2771 try:
2772 2772 globs,locs = where[0:2]
2773 2773 except:
2774 2774 try:
2775 2775 globs = locs = where[0]
2776 2776 except:
2777 2777 globs = locs = globals()
2778 2778 badblocks = []
2779 2779
2780 2780 # we also need to identify indented blocks of code when replaying
2781 2781 # logs and put them together before passing them to an exec
2782 2782 # statement. This takes a bit of regexp and look-ahead work in the
2783 2783 # file. It's easiest if we swallow the whole thing in memory
2784 2784 # first, and manually walk through the lines list moving the
2785 2785 # counter ourselves.
2786 2786 indent_re = re.compile('\s+\S')
2787 2787 xfile = open(fname)
2788 2788 filelines = xfile.readlines()
2789 2789 xfile.close()
2790 2790 nlines = len(filelines)
2791 2791 lnum = 0
2792 2792 while lnum < nlines:
2793 2793 line = filelines[lnum]
2794 2794 lnum += 1
2795 2795 # don't re-insert logger status info into cache
2796 2796 if line.startswith('#log#'):
2797 2797 continue
2798 2798 else:
2799 2799 # build a block of code (maybe a single line) for execution
2800 2800 block = line
2801 2801 try:
2802 2802 next = filelines[lnum] # lnum has already incremented
2803 2803 except:
2804 2804 next = None
2805 2805 while next and indent_re.match(next):
2806 2806 block += next
2807 2807 lnum += 1
2808 2808 try:
2809 2809 next = filelines[lnum]
2810 2810 except:
2811 2811 next = None
2812 2812 # now execute the block of one or more lines
2813 2813 try:
2814 2814 exec block in globs,locs
2815 2815 except SystemExit:
2816 2816 pass
2817 2817 except:
2818 2818 badblocks.append(block.rstrip())
2819 2819 if kw['quiet']: # restore stdout
2820 2820 sys.stdout.close()
2821 2821 sys.stdout = stdout_save
2822 2822 print 'Finished replaying log file <%s>' % fname
2823 2823 if badblocks:
2824 2824 print >> sys.stderr, ('\nThe following lines/blocks in file '
2825 2825 '<%s> reported errors:' % fname)
2826 2826
2827 2827 for badline in badblocks:
2828 2828 print >> sys.stderr, badline
2829 2829 else: # regular file execution
2830 2830 try:
2831 2831 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2832 2832 # Work around a bug in Python for Windows. The bug was
2833 2833 # fixed in in Python 2.5 r54159 and 54158, but that's still
2834 2834 # SVN Python as of March/07. For details, see:
2835 2835 # http://projects.scipy.org/ipython/ipython/ticket/123
2836 2836 try:
2837 2837 globs,locs = where[0:2]
2838 2838 except:
2839 2839 try:
2840 2840 globs = locs = where[0]
2841 2841 except:
2842 2842 globs = locs = globals()
2843 2843 exec file(fname) in globs,locs
2844 2844 else:
2845 2845 execfile(fname,*where)
2846 2846 except SyntaxError:
2847 2847 self.showsyntaxerror()
2848 2848 warn('Failure executing file: <%s>' % fname)
2849 2849 except SystemExit,status:
2850 2850 # Code that correctly sets the exit status flag to success (0)
2851 2851 # shouldn't be bothered with a traceback. Note that a plain
2852 2852 # sys.exit() does NOT set the message to 0 (it's empty) so that
2853 2853 # will still get a traceback. Note that the structure of the
2854 2854 # SystemExit exception changed between Python 2.4 and 2.5, so
2855 2855 # the checks must be done in a version-dependent way.
2856 2856 show = False
2857 2857
2858 2858 if sys.version_info[:2] > (2,5):
2859 2859 if status.message!=0 and not kw['exit_ignore']:
2860 2860 show = True
2861 2861 else:
2862 2862 if status.code and not kw['exit_ignore']:
2863 2863 show = True
2864 2864 if show:
2865 2865 self.showtraceback()
2866 2866 warn('Failure executing file: <%s>' % fname)
2867 2867 except:
2868 2868 self.showtraceback()
2869 2869 warn('Failure executing file: <%s>' % fname)
2870 2870
2871 2871 syspath_cleanup()
2872 2872
2873 2873 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now