##// END OF EJS Templates
Merge with upstream
Fernando Perez -
r1497:b2eab5e1 merge
parent child Browse files
Show More
@@ -1,647 +1,687 b''
1 1 """IPython customization API
2 2
3 3 Your one-stop module for configuring & extending ipython
4 4
5 5 The API will probably break when ipython 1.0 is released, but so
6 6 will the other configuration method (rc files).
7 7
8 8 All names prefixed by underscores are for internal use, not part
9 9 of the public api.
10 10
11 11 Below is an example that you can just put to a module and import from ipython.
12 12
13 13 A good practice is to install the config script below as e.g.
14 14
15 15 ~/.ipython/my_private_conf.py
16 16
17 17 And do
18 18
19 19 import_mod my_private_conf
20 20
21 21 in ~/.ipython/ipythonrc
22 22
23 23 That way the module is imported at startup and you can have all your
24 24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 25 stuff) in there.
26 26
27 27 -----------------------------------------------
28 28 import IPython.ipapi
29 29 ip = IPython.ipapi.get()
30 30
31 31 def ankka_f(self, arg):
32 32 print 'Ankka',self,'says uppercase:',arg.upper()
33 33
34 34 ip.expose_magic('ankka',ankka_f)
35 35
36 36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 37 ip.magic('alias helloworld echo "Hello world"')
38 38 ip.system('pwd')
39 39
40 40 ip.ex('import re')
41 41 ip.ex('''
42 42 def funcci(a,b):
43 43 print a+b
44 44 print funcci(3,4)
45 45 ''')
46 46 ip.ex('funcci(348,9)')
47 47
48 48 def jed_editor(self,filename, linenum=None):
49 49 print 'Calling my own editor, jed ... via hook!'
50 50 import os
51 51 if linenum is None: linenum = 0
52 52 os.system('jed +%d %s' % (linenum, filename))
53 53 print 'exiting jed'
54 54
55 55 ip.set_hook('editor',jed_editor)
56 56
57 57 o = ip.options
58 58 o.autocall = 2 # FULL autocall mode
59 59
60 60 print 'done!'
61 61 """
62 62
63 63 #-----------------------------------------------------------------------------
64 64 # Modules and globals
65 65
66 66 # stdlib imports
67 67 import __builtin__
68 68 import sys
69 69
70 70 # contains the most recently instantiated IPApi
71 71 _RECENT_IP = None
72 72
73 73 #-----------------------------------------------------------------------------
74 74 # Code begins
75 75
76 76 class TryNext(Exception):
77 77 """Try next hook exception.
78 78
79 79 Raise this in your hook function to indicate that the next hook handler
80 80 should be used to handle the operation. If you pass arguments to the
81 81 constructor those arguments will be used by the next hook instead of the
82 82 original ones.
83 83 """
84 84
85 85 def __init__(self, *args, **kwargs):
86 86 self.args = args
87 87 self.kwargs = kwargs
88 88
89 89
90 90 class UsageError(Exception):
91 91 """ Error in magic function arguments, etc.
92 92
93 93 Something that probably won't warrant a full traceback, but should
94 94 nevertheless interrupt a macro / batch file.
95 95 """
96 96
97 97
98 98 class IPyAutocall:
99 99 """ Instances of this class are always autocalled
100 100
101 101 This happens regardless of 'autocall' variable state. Use this to
102 102 develop macro-like mechanisms.
103 103 """
104 104
105 105 def set_ip(self,ip):
106 106 """ Will be used to set _ip point to current ipython instance b/f call
107 107
108 108 Override this method if you don't want this to happen.
109 109
110 110 """
111 111 self._ip = ip
112 112
113 113
114 114 class IPythonNotRunning:
115 115 """Dummy do-nothing class.
116 116
117 117 Instances of this class return a dummy attribute on all accesses, which
118 118 can be called and warns. This makes it easier to write scripts which use
119 119 the ipapi.get() object for informational purposes to operate both with and
120 120 without ipython. Obviously code which uses the ipython object for
121 121 computations will not work, but this allows a wider range of code to
122 122 transparently work whether ipython is being used or not."""
123 123
124 124 def __init__(self,warn=True):
125 125 if warn:
126 126 self.dummy = self._dummy_warn
127 127 else:
128 128 self.dummy = self._dummy_silent
129 129
130 130 def __str__(self):
131 131 return "<IPythonNotRunning>"
132 132
133 133 __repr__ = __str__
134 134
135 135 def __getattr__(self,name):
136 136 return self.dummy
137 137
138 138 def _dummy_warn(self,*args,**kw):
139 139 """Dummy function, which doesn't do anything but warn."""
140 140
141 141 print ("IPython is not running, this is a dummy no-op function")
142 142
143 143 def _dummy_silent(self,*args,**kw):
144 144 """Dummy function, which doesn't do anything and emits no warnings."""
145 145 pass
146 146
147 147
148 148 def get(allow_dummy=False,dummy_warn=True):
149 149 """Get an IPApi object.
150 150
151 151 If allow_dummy is true, returns an instance of IPythonNotRunning
152 152 instead of None if not running under IPython.
153 153
154 154 If dummy_warn is false, the dummy instance will be completely silent.
155 155
156 156 Running this should be the first thing you do when writing extensions that
157 157 can be imported as normal modules. You can then direct all the
158 158 configuration operations against the returned object.
159 159 """
160 160 global _RECENT_IP
161 161 if allow_dummy and not _RECENT_IP:
162 162 _RECENT_IP = IPythonNotRunning(dummy_warn)
163 163 return _RECENT_IP
164 164
165 165
166 166 class IPApi(object):
167 167 """ The actual API class for configuring IPython
168 168
169 169 You should do all of the IPython configuration by getting an IPApi object
170 170 with IPython.ipapi.get() and using the attributes and methods of the
171 171 returned object."""
172 172
173 173 def __init__(self,ip):
174 174
175 175 global _RECENT_IP
176 176
177 177 # All attributes exposed here are considered to be the public API of
178 178 # IPython. As needs dictate, some of these may be wrapped as
179 179 # properties.
180 180
181 181 self.magic = ip.ipmagic
182 182
183 183 self.system = ip.system
184 184
185 185 self.set_hook = ip.set_hook
186 186
187 187 self.set_custom_exc = ip.set_custom_exc
188 188
189 189 self.user_ns = ip.user_ns
190 190 self.user_ns['_ip'] = self
191 191
192 192 self.set_crash_handler = ip.set_crash_handler
193 193
194 194 # Session-specific data store, which can be used to store
195 195 # data that should persist through the ipython session.
196 196 self.meta = ip.meta
197 197
198 198 # The ipython instance provided
199 199 self.IP = ip
200 200
201 201 self.extensions = {}
202 202
203 203 self.dbg = DebugTools(self)
204 204
205 205 _RECENT_IP = self
206 206
207 207 # Use a property for some things which are added to the instance very
208 208 # late. I don't have time right now to disentangle the initialization
209 209 # order issues, so a property lets us delay item extraction while
210 210 # providing a normal attribute API.
211 211 def get_db(self):
212 212 """A handle to persistent dict-like database (a PickleShareDB object)"""
213 213 return self.IP.db
214 214
215 215 db = property(get_db,None,None,get_db.__doc__)
216 216
217 217 def get_options(self):
218 218 """All configurable variables."""
219 219
220 220 # catch typos by disabling new attribute creation. If new attr creation
221 221 # is in fact wanted (e.g. when exposing new options), do
222 222 # allow_new_attr(True) for the received rc struct.
223 223
224 224 self.IP.rc.allow_new_attr(False)
225 225 return self.IP.rc
226 226
227 227 options = property(get_options,None,None,get_options.__doc__)
228 228
229 229 def expose_magic(self,magicname, func):
230 230 """Expose own function as magic function for ipython
231 231
232 232 def foo_impl(self,parameter_s=''):
233 233 'My very own magic!. (Use docstrings, IPython reads them).'
234 234 print 'Magic function. Passed parameter is between < >:'
235 235 print '<%s>' % parameter_s
236 236 print 'The self object is:',self
237 237
238 238 ipapi.expose_magic('foo',foo_impl)
239 239 """
240 240
241 241 import new
242 242 im = new.instancemethod(func,self.IP, self.IP.__class__)
243 243 old = getattr(self.IP, "magic_" + magicname, None)
244 244 if old:
245 245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
246 246 (magicname,old) )
247 247
248 248 setattr(self.IP, "magic_" + magicname, im)
249 249
250 250 def ex(self,cmd):
251 251 """ Execute a normal python statement in user namespace """
252 252 exec cmd in self.user_ns
253 253
254 254 def ev(self,expr):
255 255 """ Evaluate python expression expr in user namespace
256 256
257 257 Returns the result of evaluation"""
258 258 return eval(expr,self.user_ns)
259 259
260 260 def runlines(self,lines):
261 261 """ Run the specified lines in interpreter, honoring ipython directives.
262 262
263 263 This allows %magic and !shell escape notations.
264 264
265 265 Takes either all lines in one string or list of lines.
266 266 """
267 267
268 268 def cleanup_ipy_script(script):
269 269 """ Make a script safe for _ip.runlines()
270 270
271 271 - Removes empty lines Suffixes all indented blocks that end with
272 272 - unindented lines with empty lines
273 273 """
274 274
275 275 res = []
276 276 lines = script.splitlines()
277 277
278 278 level = 0
279 279 for l in lines:
280 280 lstripped = l.lstrip()
281 281 stripped = l.strip()
282 282 if not stripped:
283 283 continue
284 284 newlevel = len(l) - len(lstripped)
285 285 def is_secondary_block_start(s):
286 286 if not s.endswith(':'):
287 287 return False
288 288 if (s.startswith('elif') or
289 289 s.startswith('else') or
290 290 s.startswith('except') or
291 291 s.startswith('finally')):
292 292 return True
293 293
294 294 if level > 0 and newlevel == 0 and \
295 295 not is_secondary_block_start(stripped):
296 296 # add empty line
297 297 res.append('')
298 298
299 299 res.append(l)
300 300 level = newlevel
301 301 return '\n'.join(res) + '\n'
302 302
303 303 if isinstance(lines,basestring):
304 304 script = lines
305 305 else:
306 306 script = '\n'.join(lines)
307 307 clean=cleanup_ipy_script(script)
308 308 # print "_ip.runlines() script:\n",clean # dbg
309 309 self.IP.runlines(clean)
310 310
311 311 def to_user_ns(self,vars, interactive = True):
312 312 """Inject a group of variables into the IPython user namespace.
313 313
314 314 Inputs:
315 315
316 316 - vars: string with variable names separated by whitespace, or a
317 317 dict with name/value pairs.
318 318
319 319 - interactive: if True (default), the var will be listed with
320 320 %whos et. al.
321 321
322 322 This utility routine is meant to ease interactive debugging work,
323 323 where you want to easily propagate some internal variable in your code
324 324 up to the interactive namespace for further exploration.
325 325
326 326 When you run code via %run, globals in your script become visible at
327 327 the interactive prompt, but this doesn't happen for locals inside your
328 328 own functions and methods. Yet when debugging, it is common to want
329 329 to explore some internal variables further at the interactive propmt.
330 330
331 331 Examples:
332 332
333 333 To use this, you first must obtain a handle on the ipython object as
334 334 indicated above, via:
335 335
336 336 import IPython.ipapi
337 337 ip = IPython.ipapi.get()
338 338
339 339 Once this is done, inside a routine foo() where you want to expose
340 340 variables x and y, you do the following:
341 341
342 342 def foo():
343 343 ...
344 344 x = your_computation()
345 345 y = something_else()
346 346
347 347 # This pushes x and y to the interactive prompt immediately, even
348 348 # if this routine crashes on the next line after:
349 349 ip.to_user_ns('x y')
350 350 ...
351 351
352 352 # To expose *ALL* the local variables from the function, use:
353 353 ip.to_user_ns(locals())
354 354
355 355 ...
356 356 # return
357 357
358 358
359 359 If you need to rename variables, the dict input makes it easy. For
360 360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
361 361 in IPython user namespace:
362 362
363 363 ip.to_user_ns(dict(x=foo,y=bar))
364 364 """
365 365
366 366 # print 'vars given:',vars # dbg
367 367
368 368 # We need a dict of name/value pairs to do namespace updates.
369 369 if isinstance(vars,dict):
370 370 # If a dict was given, no need to change anything.
371 371 vdict = vars
372 372 elif isinstance(vars,basestring):
373 373 # If a string with names was given, get the caller's frame to
374 374 # evaluate the given names in
375 375 cf = sys._getframe(1)
376 376 vdict = {}
377 377 for name in vars.split():
378 378 try:
379 379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
380 380 except:
381 381 print ('could not get var. %s from %s' %
382 382 (name,cf.f_code.co_name))
383 383 else:
384 384 raise ValueError('vars must be a string or a dict')
385 385
386 386 # Propagate variables to user namespace
387 387 self.user_ns.update(vdict)
388 388
389 389 # And configure interactive visibility
390 390 config_ns = self.IP.user_config_ns
391 391 if interactive:
392 392 for name,val in vdict.iteritems():
393 393 config_ns.pop(name,None)
394 394 else:
395 395 for name,val in vdict.iteritems():
396 396 config_ns[name] = val
397 397
398 398 def expand_alias(self,line):
399 399 """ Expand an alias in the command line
400 400
401 401 Returns the provided command line, possibly with the first word
402 402 (command) translated according to alias expansion rules.
403 403
404 404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
405 405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
406 406 """
407 407
408 408 pre,fn,rest = self.IP.split_user_input(line)
409 409 res = pre + self.IP.expand_aliases(fn,rest)
410 410 return res
411 411
412 412 def itpl(self, s, depth = 1):
413 413 """ Expand Itpl format string s.
414 414
415 415 Only callable from command line (i.e. prefilter results);
416 416 If you use in your scripts, you need to use a bigger depth!
417 417 """
418 418 return self.IP.var_expand(s, depth)
419 419
420 420 def defalias(self, name, cmd):
421 421 """ Define a new alias
422 422
423 423 _ip.defalias('bb','bldmake bldfiles')
424 424
425 425 Creates a new alias named 'bb' in ipython user namespace
426 426 """
427 427
428 428 self.dbg.check_hotname(name)
429 429
430 430 if name in self.IP.alias_table:
431 431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
432 432 % (name, cmd, self.IP.alias_table[name]))
433 433
434 434 if callable(cmd):
435 435 self.IP.alias_table[name] = cmd
436 436 import IPython.shadowns
437 437 setattr(IPython.shadowns, name,cmd)
438 438 return
439 439
440 440 if isinstance(cmd,basestring):
441 441 nargs = cmd.count('%s')
442 442 if nargs>0 and cmd.find('%l')>=0:
443 443 raise Exception('The %s and %l specifiers are mutually '
444 444 'exclusive in alias definitions.')
445 445
446 446 self.IP.alias_table[name] = (nargs,cmd)
447 447 return
448 448
449 449 # just put it in - it's probably (0,'foo')
450 450 self.IP.alias_table[name] = cmd
451 451
452 452 def defmacro(self, *args):
453 453 """ Define a new macro
454 454
455 455 2 forms of calling:
456 456
457 457 mac = _ip.defmacro('print "hello"\nprint "world"')
458 458
459 459 (doesn't put the created macro on user namespace)
460 460
461 461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
462 462
463 463 (creates a macro named 'build' in user namespace)
464 464 """
465 465
466 466 import IPython.macro
467 467
468 468 if len(args) == 1:
469 469 return IPython.macro.Macro(args[0])
470 470 elif len(args) == 2:
471 471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
472 472 else:
473 473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
474 474
475 475 def set_next_input(self, s):
476 476 """ Sets the 'default' input string for the next command line.
477 477
478 478 Requires readline.
479 479
480 480 Example:
481 481
482 482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
483 483 [D:\ipython]|2> Hello Word_ # cursor is here
484 484 """
485 485
486 486 self.IP.rl_next_input = s
487 487
488 488 def load(self, mod):
489 489 """ Load an extension.
490 490
491 491 Some modules should (or must) be 'load()':ed, rather than just imported.
492 492
493 493 Loading will do:
494 494
495 495 - run init_ipython(ip)
496 496 - run ipython_firstrun(ip)
497 497 """
498 498
499 499 if mod in self.extensions:
500 500 # just to make sure we don't init it twice
501 501 # note that if you 'load' a module that has already been
502 502 # imported, init_ipython gets run anyway
503 503
504 504 return self.extensions[mod]
505 505 __import__(mod)
506 506 m = sys.modules[mod]
507 507 if hasattr(m,'init_ipython'):
508 508 m.init_ipython(self)
509 509
510 510 if hasattr(m,'ipython_firstrun'):
511 511 already_loaded = self.db.get('firstrun_done', set())
512 512 if mod not in already_loaded:
513 513 m.ipython_firstrun(self)
514 514 already_loaded.add(mod)
515 515 self.db['firstrun_done'] = already_loaded
516 516
517 517 self.extensions[mod] = m
518 518 return m
519 519
520 520
521 521 class DebugTools:
522 522 """ Used for debugging mishaps in api usage
523 523
524 524 So far, tracing redefinitions is supported.
525 525 """
526 526
527 527 def __init__(self, ip):
528 528 self.ip = ip
529 529 self.debugmode = False
530 530 self.hotnames = set()
531 531
532 532 def hotname(self, name_to_catch):
533 533 self.hotnames.add(name_to_catch)
534 534
535 535 def debug_stack(self, msg = None):
536 536 if not self.debugmode:
537 537 return
538 538
539 539 import traceback
540 540 if msg is not None:
541 541 print '====== %s ========' % msg
542 542 traceback.print_stack()
543 543
544 544 def check_hotname(self,name):
545 545 if name in self.hotnames:
546 546 self.debug_stack( "HotName '%s' caught" % name)
547 547
548 548
549 549 def launch_new_instance(user_ns = None,shellclass = None):
550 550 """ Make and start a new ipython instance.
551 551
552 552 This can be called even without having an already initialized
553 553 ipython session running.
554 554
555 555 This is also used as the egg entry point for the 'ipython' script.
556 556
557 557 """
558 558 ses = make_session(user_ns,shellclass)
559 559 ses.mainloop()
560 560
561 561
562 562 def make_user_ns(user_ns = None):
563 563 """Return a valid user interactive namespace.
564 564
565 565 This builds a dict with the minimal information needed to operate as a
566 566 valid IPython user namespace, which you can pass to the various embedding
567 567 classes in ipython.
568
569 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
570 to make both the local and global namespace objects simultaneously.
571
572 :Parameters:
573 user_ns : dict-like, optional
574 The current user namespace. The items in this namespace should be
575 included in the output. If None, an appropriate blank namespace
576 should be created.
577
578 :Returns:
579 A dictionary-like object to be used as the local namespace of the
580 interpreter.
568 581 """
569 582
570 583 raise NotImplementedError
571 584
572 585
573 586 def make_user_global_ns(ns = None):
574 587 """Return a valid user global namespace.
575 588
576 589 Similar to make_user_ns(), but global namespaces are really only needed in
577 590 embedded applications, where there is a distinction between the user's
578 interactive namespace and the global one where ipython is running."""
591 interactive namespace and the global one where ipython is running.
592
593 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
594 to make both the local and global namespace objects simultaneously.
595
596 :Parameters:
597 ns : dict, optional
598 The current user global namespace. The items in this namespace
599 should be included in the output. If None, an appropriate blank
600 namespace should be created.
601
602 :Returns:
603 A true dict to be used as the global namespace of the interpreter.
604 """
579 605
580 606 raise NotImplementedError
581 607
582 608 # Record the true objects in order to be able to test if the user has overridden
583 609 # these API functions.
584 610 _make_user_ns = make_user_ns
585 611 _make_user_global_ns = make_user_global_ns
586 612
587 613
588 614 def make_user_namespaces(user_ns = None,user_global_ns = None):
589 615 """Return a valid local and global user interactive namespaces.
590 616
591 617 This builds a dict with the minimal information needed to operate as a
592 618 valid IPython user namespace, which you can pass to the various embedding
593 619 classes in ipython. The default implementation returns the same dict for
594 620 both the locals and the globals to allow functions to refer to variables in
595 621 the namespace. Customized implementations can return different dicts. The
596 622 locals dictionary can actually be anything following the basic mapping
597 623 protocol of a dict, but the globals dict must be a true dict, not even
598 624 a subclass. It is recommended that any custom object for the locals
599 625 namespace synchronize with the globals dict somehow.
600 626
601 627 Raises TypeError if the provided globals namespace is not a true dict.
628
629 :Parameters:
630 user_ns : dict-like, optional
631 The current user namespace. The items in this namespace should be
632 included in the output. If None, an appropriate blank namespace
633 should be created.
634 user_global_ns : dict, optional
635 The current user global namespace. The items in this namespace
636 should be included in the output. If None, an appropriate blank
637 namespace should be created.
638
639 :Returns:
640 A tuple pair of dictionary-like object to be used as the local namespace
641 of the interpreter and a dict to be used as the global namespace.
602 642 """
603 643
604 644 if user_ns is None:
605 645 if make_user_ns is not _make_user_ns:
606 646 # Old API overridden.
607 647 # FIXME: Issue DeprecationWarning, or just let the old API live on?
608 648 user_ns = make_user_ns(user_ns)
609 649 else:
610 650 # Set __name__ to __main__ to better match the behavior of the
611 651 # normal interpreter.
612 652 user_ns = {'__name__' :'__main__',
613 653 '__builtins__' : __builtin__,
614 654 }
615 655 else:
616 656 user_ns.setdefault('__name__','__main__')
617 657 user_ns.setdefault('__builtins__',__builtin__)
618 658
619 659 if user_global_ns is None:
620 660 if make_user_global_ns is not _make_user_global_ns:
621 661 # Old API overridden.
622 662 user_global_ns = make_user_global_ns(user_global_ns)
623 663 else:
624 664 user_global_ns = user_ns
625 665 if type(user_global_ns) is not dict:
626 666 raise TypeError("user_global_ns must be a true dict; got %r"
627 667 % type(user_global_ns))
628 668
629 669 return user_ns, user_global_ns
630 670
631 671
632 672 def make_session(user_ns = None, shellclass = None):
633 673 """Makes, but does not launch an IPython session.
634 674
635 675 Later on you can call obj.mainloop() on the returned object.
636 676
637 677 Inputs:
638 678
639 679 - user_ns(None): a dict to be used as the user's namespace with initial
640 680 data.
641 681
642 682 WARNING: This should *not* be run when a session exists already."""
643 683
644 684 import IPython.Shell
645 685 if shellclass is None:
646 686 return IPython.Shell.start(user_ns)
647 687 return shellclass(user_ns = user_ns)
General Comments 0
You need to be logged in to leave comments. Login now