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