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