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