##// END OF EJS Templates
Don't try to pass shell up kwargs from Magics class...
Thomas Kluyver -
Show More
@@ -1,704 +1,703 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4 from __future__ import print_function
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 9 # Copyright (C) 2008 The IPython Development Team
10 10
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18 # Stdlib
19 19 import os
20 20 import re
21 21 import sys
22 22 import types
23 23 from getopt import getopt, GetoptError
24 24
25 25 # Our own
26 26 from traitlets.config.configurable import Configurable
27 27 from IPython.core import oinspect
28 28 from IPython.core.error import UsageError
29 29 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
30 30 from decorator import decorator
31 31 from IPython.utils.ipstruct import Struct
32 32 from IPython.utils.process import arg_split
33 33 from IPython.utils.py3compat import string_types, iteritems
34 34 from IPython.utils.text import dedent
35 35 from traitlets import Bool, Dict, Instance
36 36 from IPython.utils.warn import error
37 37
38 38 #-----------------------------------------------------------------------------
39 39 # Globals
40 40 #-----------------------------------------------------------------------------
41 41
42 42 # A dict we'll use for each class that has magics, used as temporary storage to
43 43 # pass information between the @line/cell_magic method decorators and the
44 44 # @magics_class class decorator, because the method decorators have no
45 45 # access to the class when they run. See for more details:
46 46 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
47 47
48 48 magics = dict(line={}, cell={})
49 49
50 50 magic_kinds = ('line', 'cell')
51 51 magic_spec = ('line', 'cell', 'line_cell')
52 52 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
53 53
54 54 #-----------------------------------------------------------------------------
55 55 # Utility classes and functions
56 56 #-----------------------------------------------------------------------------
57 57
58 58 class Bunch: pass
59 59
60 60
61 61 def on_off(tag):
62 62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 63 return ['OFF','ON'][tag]
64 64
65 65
66 66 def compress_dhist(dh):
67 67 """Compress a directory history into a new one with at most 20 entries.
68 68
69 69 Return a new list made from the first and last 10 elements of dhist after
70 70 removal of duplicates.
71 71 """
72 72 head, tail = dh[:-10], dh[-10:]
73 73
74 74 newhead = []
75 75 done = set()
76 76 for h in head:
77 77 if h in done:
78 78 continue
79 79 newhead.append(h)
80 80 done.add(h)
81 81
82 82 return newhead + tail
83 83
84 84
85 85 def needs_local_scope(func):
86 86 """Decorator to mark magic functions which need to local scope to run."""
87 87 func.needs_local_scope = True
88 88 return func
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Class and method decorators for registering magics
92 92 #-----------------------------------------------------------------------------
93 93
94 94 def magics_class(cls):
95 95 """Class decorator for all subclasses of the main Magics class.
96 96
97 97 Any class that subclasses Magics *must* also apply this decorator, to
98 98 ensure that all the methods that have been decorated as line/cell magics
99 99 get correctly registered in the class instance. This is necessary because
100 100 when method decorators run, the class does not exist yet, so they
101 101 temporarily store their information into a module global. Application of
102 102 this class decorator copies that global data to the class instance and
103 103 clears the global.
104 104
105 105 Obviously, this mechanism is not thread-safe, which means that the
106 106 *creation* of subclasses of Magic should only be done in a single-thread
107 107 context. Instantiation of the classes has no restrictions. Given that
108 108 these classes are typically created at IPython startup time and before user
109 109 application code becomes active, in practice this should not pose any
110 110 problems.
111 111 """
112 112 cls.registered = True
113 113 cls.magics = dict(line = magics['line'],
114 114 cell = magics['cell'])
115 115 magics['line'] = {}
116 116 magics['cell'] = {}
117 117 return cls
118 118
119 119
120 120 def record_magic(dct, magic_kind, magic_name, func):
121 121 """Utility function to store a function as a magic of a specific kind.
122 122
123 123 Parameters
124 124 ----------
125 125 dct : dict
126 126 A dictionary with 'line' and 'cell' subdicts.
127 127
128 128 magic_kind : str
129 129 Kind of magic to be stored.
130 130
131 131 magic_name : str
132 132 Key to store the magic as.
133 133
134 134 func : function
135 135 Callable object to store.
136 136 """
137 137 if magic_kind == 'line_cell':
138 138 dct['line'][magic_name] = dct['cell'][magic_name] = func
139 139 else:
140 140 dct[magic_kind][magic_name] = func
141 141
142 142
143 143 def validate_type(magic_kind):
144 144 """Ensure that the given magic_kind is valid.
145 145
146 146 Check that the given magic_kind is one of the accepted spec types (stored
147 147 in the global `magic_spec`), raise ValueError otherwise.
148 148 """
149 149 if magic_kind not in magic_spec:
150 150 raise ValueError('magic_kind must be one of %s, %s given' %
151 151 magic_kinds, magic_kind)
152 152
153 153
154 154 # The docstrings for the decorator below will be fairly similar for the two
155 155 # types (method and function), so we generate them here once and reuse the
156 156 # templates below.
157 157 _docstring_template = \
158 158 """Decorate the given {0} as {1} magic.
159 159
160 160 The decorator can be used with or without arguments, as follows.
161 161
162 162 i) without arguments: it will create a {1} magic named as the {0} being
163 163 decorated::
164 164
165 165 @deco
166 166 def foo(...)
167 167
168 168 will create a {1} magic named `foo`.
169 169
170 170 ii) with one string argument: which will be used as the actual name of the
171 171 resulting magic::
172 172
173 173 @deco('bar')
174 174 def foo(...)
175 175
176 176 will create a {1} magic named `bar`.
177 177 """
178 178
179 179 # These two are decorator factories. While they are conceptually very similar,
180 180 # there are enough differences in the details that it's simpler to have them
181 181 # written as completely standalone functions rather than trying to share code
182 182 # and make a single one with convoluted logic.
183 183
184 184 def _method_magic_marker(magic_kind):
185 185 """Decorator factory for methods in Magics subclasses.
186 186 """
187 187
188 188 validate_type(magic_kind)
189 189
190 190 # This is a closure to capture the magic_kind. We could also use a class,
191 191 # but it's overkill for just that one bit of state.
192 192 def magic_deco(arg):
193 193 call = lambda f, *a, **k: f(*a, **k)
194 194
195 195 if callable(arg):
196 196 # "Naked" decorator call (just @foo, no args)
197 197 func = arg
198 198 name = func.__name__
199 199 retval = decorator(call, func)
200 200 record_magic(magics, magic_kind, name, name)
201 201 elif isinstance(arg, string_types):
202 202 # Decorator called with arguments (@foo('bar'))
203 203 name = arg
204 204 def mark(func, *a, **kw):
205 205 record_magic(magics, magic_kind, name, func.__name__)
206 206 return decorator(call, func)
207 207 retval = mark
208 208 else:
209 209 raise TypeError("Decorator can only be called with "
210 210 "string or function")
211 211 return retval
212 212
213 213 # Ensure the resulting decorator has a usable docstring
214 214 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
215 215 return magic_deco
216 216
217 217
218 218 def _function_magic_marker(magic_kind):
219 219 """Decorator factory for standalone functions.
220 220 """
221 221 validate_type(magic_kind)
222 222
223 223 # This is a closure to capture the magic_kind. We could also use a class,
224 224 # but it's overkill for just that one bit of state.
225 225 def magic_deco(arg):
226 226 call = lambda f, *a, **k: f(*a, **k)
227 227
228 228 # Find get_ipython() in the caller's namespace
229 229 caller = sys._getframe(1)
230 230 for ns in ['f_locals', 'f_globals', 'f_builtins']:
231 231 get_ipython = getattr(caller, ns).get('get_ipython')
232 232 if get_ipython is not None:
233 233 break
234 234 else:
235 235 raise NameError('Decorator can only run in context where '
236 236 '`get_ipython` exists')
237 237
238 238 ip = get_ipython()
239 239
240 240 if callable(arg):
241 241 # "Naked" decorator call (just @foo, no args)
242 242 func = arg
243 243 name = func.__name__
244 244 ip.register_magic_function(func, magic_kind, name)
245 245 retval = decorator(call, func)
246 246 elif isinstance(arg, string_types):
247 247 # Decorator called with arguments (@foo('bar'))
248 248 name = arg
249 249 def mark(func, *a, **kw):
250 250 ip.register_magic_function(func, magic_kind, name)
251 251 return decorator(call, func)
252 252 retval = mark
253 253 else:
254 254 raise TypeError("Decorator can only be called with "
255 255 "string or function")
256 256 return retval
257 257
258 258 # Ensure the resulting decorator has a usable docstring
259 259 ds = _docstring_template.format('function', magic_kind)
260 260
261 261 ds += dedent("""
262 262 Note: this decorator can only be used in a context where IPython is already
263 263 active, so that the `get_ipython()` call succeeds. You can therefore use
264 264 it in your startup files loaded after IPython initializes, but *not* in the
265 265 IPython configuration file itself, which is executed before IPython is
266 266 fully up and running. Any file located in the `startup` subdirectory of
267 267 your configuration profile will be OK in this sense.
268 268 """)
269 269
270 270 magic_deco.__doc__ = ds
271 271 return magic_deco
272 272
273 273
274 274 # Create the actual decorators for public use
275 275
276 276 # These three are used to decorate methods in class definitions
277 277 line_magic = _method_magic_marker('line')
278 278 cell_magic = _method_magic_marker('cell')
279 279 line_cell_magic = _method_magic_marker('line_cell')
280 280
281 281 # These three decorate standalone functions and perform the decoration
282 282 # immediately. They can only run where get_ipython() works
283 283 register_line_magic = _function_magic_marker('line')
284 284 register_cell_magic = _function_magic_marker('cell')
285 285 register_line_cell_magic = _function_magic_marker('line_cell')
286 286
287 287 #-----------------------------------------------------------------------------
288 288 # Core Magic classes
289 289 #-----------------------------------------------------------------------------
290 290
291 291 class MagicsManager(Configurable):
292 292 """Object that handles all magic-related functionality for IPython.
293 293 """
294 294 # Non-configurable class attributes
295 295
296 296 # A two-level dict, first keyed by magic type, then by magic function, and
297 297 # holding the actual callable object as value. This is the dict used for
298 298 # magic function dispatch
299 299 magics = Dict()
300 300
301 301 # A registry of the original objects that we've been given holding magics.
302 302 registry = Dict()
303 303
304 304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
305 305
306 306 auto_magic = Bool(True, config=True, help=
307 307 "Automatically call line magics without requiring explicit % prefix")
308 308
309 309 def _auto_magic_changed(self, name, value):
310 310 self.shell.automagic = value
311 311
312 312 _auto_status = [
313 313 'Automagic is OFF, % prefix IS needed for line magics.',
314 314 'Automagic is ON, % prefix IS NOT needed for line magics.']
315 315
316 316 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
317 317
318 318 def __init__(self, shell=None, config=None, user_magics=None, **traits):
319 319
320 320 super(MagicsManager, self).__init__(shell=shell, config=config,
321 321 user_magics=user_magics, **traits)
322 322 self.magics = dict(line={}, cell={})
323 323 # Let's add the user_magics to the registry for uniformity, so *all*
324 324 # registered magic containers can be found there.
325 325 self.registry[user_magics.__class__.__name__] = user_magics
326 326
327 327 def auto_status(self):
328 328 """Return descriptive string with automagic status."""
329 329 return self._auto_status[self.auto_magic]
330 330
331 331 def lsmagic(self):
332 332 """Return a dict of currently available magic functions.
333 333
334 334 The return dict has the keys 'line' and 'cell', corresponding to the
335 335 two types of magics we support. Each value is a list of names.
336 336 """
337 337 return self.magics
338 338
339 339 def lsmagic_docs(self, brief=False, missing=''):
340 340 """Return dict of documentation of magic functions.
341 341
342 342 The return dict has the keys 'line' and 'cell', corresponding to the
343 343 two types of magics we support. Each value is a dict keyed by magic
344 344 name whose value is the function docstring. If a docstring is
345 345 unavailable, the value of `missing` is used instead.
346 346
347 347 If brief is True, only the first line of each docstring will be returned.
348 348 """
349 349 docs = {}
350 350 for m_type in self.magics:
351 351 m_docs = {}
352 352 for m_name, m_func in iteritems(self.magics[m_type]):
353 353 if m_func.__doc__:
354 354 if brief:
355 355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
356 356 else:
357 357 m_docs[m_name] = m_func.__doc__.rstrip()
358 358 else:
359 359 m_docs[m_name] = missing
360 360 docs[m_type] = m_docs
361 361 return docs
362 362
363 363 def register(self, *magic_objects):
364 364 """Register one or more instances of Magics.
365 365
366 366 Take one or more classes or instances of classes that subclass the main
367 367 `core.Magic` class, and register them with IPython to use the magic
368 368 functions they provide. The registration process will then ensure that
369 369 any methods that have decorated to provide line and/or cell magics will
370 370 be recognized with the `%x`/`%%x` syntax as a line/cell magic
371 371 respectively.
372 372
373 373 If classes are given, they will be instantiated with the default
374 374 constructor. If your classes need a custom constructor, you should
375 375 instanitate them first and pass the instance.
376 376
377 377 The provided arguments can be an arbitrary mix of classes and instances.
378 378
379 379 Parameters
380 380 ----------
381 381 magic_objects : one or more classes or instances
382 382 """
383 383 # Start by validating them to ensure they have all had their magic
384 384 # methods registered at the instance level
385 385 for m in magic_objects:
386 386 if not m.registered:
387 387 raise ValueError("Class of magics %r was constructed without "
388 388 "the @register_magics class decorator")
389 389 if isinstance(m, type):
390 390 # If we're given an uninstantiated class
391 391 m = m(shell=self.shell)
392 392
393 393 # Now that we have an instance, we can register it and update the
394 394 # table of callables
395 395 self.registry[m.__class__.__name__] = m
396 396 for mtype in magic_kinds:
397 397 self.magics[mtype].update(m.magics[mtype])
398 398
399 399 def register_function(self, func, magic_kind='line', magic_name=None):
400 400 """Expose a standalone function as magic function for IPython.
401 401
402 402 This will create an IPython magic (line, cell or both) from a
403 403 standalone function. The functions should have the following
404 404 signatures:
405 405
406 406 * For line magics: `def f(line)`
407 407 * For cell magics: `def f(line, cell)`
408 408 * For a function that does both: `def f(line, cell=None)`
409 409
410 410 In the latter case, the function will be called with `cell==None` when
411 411 invoked as `%f`, and with cell as a string when invoked as `%%f`.
412 412
413 413 Parameters
414 414 ----------
415 415 func : callable
416 416 Function to be registered as a magic.
417 417
418 418 magic_kind : str
419 419 Kind of magic, one of 'line', 'cell' or 'line_cell'
420 420
421 421 magic_name : optional str
422 422 If given, the name the magic will have in the IPython namespace. By
423 423 default, the name of the function itself is used.
424 424 """
425 425
426 426 # Create the new method in the user_magics and register it in the
427 427 # global table
428 428 validate_type(magic_kind)
429 429 magic_name = func.__name__ if magic_name is None else magic_name
430 430 setattr(self.user_magics, magic_name, func)
431 431 record_magic(self.magics, magic_kind, magic_name, func)
432 432
433 433 def define_magic(self, name, func):
434 434 """[Deprecated] Expose own function as magic function for IPython.
435 435
436 436 Will be removed in IPython 5.0
437 437
438 438 Example::
439 439
440 440 def foo_impl(self, parameter_s=''):
441 441 'My very own magic!. (Use docstrings, IPython reads them).'
442 442 print 'Magic function. Passed parameter is between < >:'
443 443 print '<%s>' % parameter_s
444 444 print 'The self object is:', self
445 445
446 446 ip.define_magic('foo',foo_impl)
447 447 """
448 448 meth = types.MethodType(func, self.user_magics)
449 449 setattr(self.user_magics, name, meth)
450 450 record_magic(self.magics, 'line', name, meth)
451 451
452 452 def register_alias(self, alias_name, magic_name, magic_kind='line'):
453 453 """Register an alias to a magic function.
454 454
455 455 The alias is an instance of :class:`MagicAlias`, which holds the
456 456 name and kind of the magic it should call. Binding is done at
457 457 call time, so if the underlying magic function is changed the alias
458 458 will call the new function.
459 459
460 460 Parameters
461 461 ----------
462 462 alias_name : str
463 463 The name of the magic to be registered.
464 464
465 465 magic_name : str
466 466 The name of an existing magic.
467 467
468 468 magic_kind : str
469 469 Kind of magic, one of 'line' or 'cell'
470 470 """
471 471
472 472 # `validate_type` is too permissive, as it allows 'line_cell'
473 473 # which we do not handle.
474 474 if magic_kind not in magic_kinds:
475 475 raise ValueError('magic_kind must be one of %s, %s given' %
476 476 magic_kinds, magic_kind)
477 477
478 478 alias = MagicAlias(self.shell, magic_name, magic_kind)
479 479 setattr(self.user_magics, alias_name, alias)
480 480 record_magic(self.magics, magic_kind, alias_name, alias)
481 481
482 482 # Key base class that provides the central functionality for magics.
483 483
484 484
485 485 class Magics(Configurable):
486 486 """Base class for implementing magic functions.
487 487
488 488 Shell functions which can be reached as %function_name. All magic
489 489 functions should accept a string, which they can parse for their own
490 490 needs. This can make some functions easier to type, eg `%cd ../`
491 491 vs. `%cd("../")`
492 492
493 493 Classes providing magic functions need to subclass this class, and they
494 494 MUST:
495 495
496 496 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
497 497 individual methods as magic functions, AND
498 498
499 499 - Use the class decorator `@magics_class` to ensure that the magic
500 500 methods are properly registered at the instance level upon instance
501 501 initialization.
502 502
503 503 See :mod:`magic_functions` for examples of actual implementation classes.
504 504 """
505 505 # Dict holding all command-line options for each magic.
506 506 options_table = None
507 507 # Dict for the mapping of magic names to methods, set by class decorator
508 508 magics = None
509 509 # Flag to check that the class decorator was properly applied
510 510 registered = False
511 511 # Instance of IPython shell
512 512 shell = None
513 513
514 514 def __init__(self, shell=None, **kwargs):
515 515 if not(self.__class__.registered):
516 516 raise ValueError('Magics subclass without registration - '
517 517 'did you forget to apply @magics_class?')
518 518 if shell is not None:
519 519 if hasattr(shell, 'configurables'):
520 520 shell.configurables.append(self)
521 521 if hasattr(shell, 'config'):
522 522 kwargs.setdefault('parent', shell)
523 kwargs['shell'] = shell
524 523
525 524 self.shell = shell
526 525 self.options_table = {}
527 526 # The method decorators are run when the instance doesn't exist yet, so
528 527 # they can only record the names of the methods they are supposed to
529 528 # grab. Only now, that the instance exists, can we create the proper
530 529 # mapping to bound methods. So we read the info off the original names
531 530 # table and replace each method name by the actual bound method.
532 531 # But we mustn't clobber the *class* mapping, in case of multiple instances.
533 532 class_magics = self.magics
534 533 self.magics = {}
535 534 for mtype in magic_kinds:
536 535 tab = self.magics[mtype] = {}
537 536 cls_tab = class_magics[mtype]
538 537 for magic_name, meth_name in iteritems(cls_tab):
539 538 if isinstance(meth_name, string_types):
540 539 # it's a method name, grab it
541 540 tab[magic_name] = getattr(self, meth_name)
542 541 else:
543 542 # it's the real thing
544 543 tab[magic_name] = meth_name
545 544 # Configurable **needs** to be initiated at the end or the config
546 545 # magics get screwed up.
547 546 super(Magics, self).__init__(**kwargs)
548 547
549 548 def arg_err(self,func):
550 549 """Print docstring if incorrect arguments were passed"""
551 550 print('Error in arguments:')
552 551 print(oinspect.getdoc(func))
553 552
554 553 def format_latex(self, strng):
555 554 """Format a string for latex inclusion."""
556 555
557 556 # Characters that need to be escaped for latex:
558 557 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
559 558 # Magic command names as headers:
560 559 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
561 560 re.MULTILINE)
562 561 # Magic commands
563 562 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
564 563 re.MULTILINE)
565 564 # Paragraph continue
566 565 par_re = re.compile(r'\\$',re.MULTILINE)
567 566
568 567 # The "\n" symbol
569 568 newline_re = re.compile(r'\\n')
570 569
571 570 # Now build the string for output:
572 571 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
573 572 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
574 573 strng)
575 574 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
576 575 strng = par_re.sub(r'\\\\',strng)
577 576 strng = escape_re.sub(r'\\\1',strng)
578 577 strng = newline_re.sub(r'\\textbackslash{}n',strng)
579 578 return strng
580 579
581 580 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
582 581 """Parse options passed to an argument string.
583 582
584 583 The interface is similar to that of :func:`getopt.getopt`, but it
585 584 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
586 585 and the stripped argument string still as a string.
587 586
588 587 arg_str is quoted as a true sys.argv vector by using shlex.split.
589 588 This allows us to easily expand variables, glob files, quote
590 589 arguments, etc.
591 590
592 591 Parameters
593 592 ----------
594 593
595 594 arg_str : str
596 595 The arguments to parse.
597 596
598 597 opt_str : str
599 598 The options specification.
600 599
601 600 mode : str, default 'string'
602 601 If given as 'list', the argument string is returned as a list (split
603 602 on whitespace) instead of a string.
604 603
605 604 list_all : bool, default False
606 605 Put all option values in lists. Normally only options
607 606 appearing more than once are put in a list.
608 607
609 608 posix : bool, default True
610 609 Whether to split the input line in POSIX mode or not, as per the
611 610 conventions outlined in the :mod:`shlex` module from the standard
612 611 library.
613 612 """
614 613
615 614 # inject default options at the beginning of the input line
616 615 caller = sys._getframe(1).f_code.co_name
617 616 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
618 617
619 618 mode = kw.get('mode','string')
620 619 if mode not in ['string','list']:
621 620 raise ValueError('incorrect mode given: %s' % mode)
622 621 # Get options
623 622 list_all = kw.get('list_all',0)
624 623 posix = kw.get('posix', os.name == 'posix')
625 624 strict = kw.get('strict', True)
626 625
627 626 # Check if we have more than one argument to warrant extra processing:
628 627 odict = {} # Dictionary with options
629 628 args = arg_str.split()
630 629 if len(args) >= 1:
631 630 # If the list of inputs only has 0 or 1 thing in it, there's no
632 631 # need to look for options
633 632 argv = arg_split(arg_str, posix, strict)
634 633 # Do regular option processing
635 634 try:
636 635 opts,args = getopt(argv, opt_str, long_opts)
637 636 except GetoptError as e:
638 637 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
639 638 " ".join(long_opts)))
640 639 for o,a in opts:
641 640 if o.startswith('--'):
642 641 o = o[2:]
643 642 else:
644 643 o = o[1:]
645 644 try:
646 645 odict[o].append(a)
647 646 except AttributeError:
648 647 odict[o] = [odict[o],a]
649 648 except KeyError:
650 649 if list_all:
651 650 odict[o] = [a]
652 651 else:
653 652 odict[o] = a
654 653
655 654 # Prepare opts,args for return
656 655 opts = Struct(odict)
657 656 if mode == 'string':
658 657 args = ' '.join(args)
659 658
660 659 return opts,args
661 660
662 661 def default_option(self, fn, optstr):
663 662 """Make an entry in the options_table for fn, with value optstr"""
664 663
665 664 if fn not in self.lsmagic():
666 665 error("%s is not a magic function" % fn)
667 666 self.options_table[fn] = optstr
668 667
669 668
670 669 class MagicAlias(object):
671 670 """An alias to another magic function.
672 671
673 672 An alias is determined by its magic name and magic kind. Lookup
674 673 is done at call time, so if the underlying magic changes the alias
675 674 will call the new function.
676 675
677 676 Use the :meth:`MagicsManager.register_alias` method or the
678 677 `%alias_magic` magic function to create and register a new alias.
679 678 """
680 679 def __init__(self, shell, magic_name, magic_kind):
681 680 self.shell = shell
682 681 self.magic_name = magic_name
683 682 self.magic_kind = magic_kind
684 683
685 684 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
686 685 self.__doc__ = "Alias for `%s`." % self.pretty_target
687 686
688 687 self._in_call = False
689 688
690 689 def __call__(self, *args, **kwargs):
691 690 """Call the magic alias."""
692 691 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
693 692 if fn is None:
694 693 raise UsageError("Magic `%s` not found." % self.pretty_target)
695 694
696 695 # Protect against infinite recursion.
697 696 if self._in_call:
698 697 raise UsageError("Infinite recursion detected; "
699 698 "magic aliases cannot call themselves.")
700 699 self._in_call = True
701 700 try:
702 701 return fn(*args, **kwargs)
703 702 finally:
704 703 self._in_call = False
General Comments 0
You need to be logged in to leave comments. Login now