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