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