Execute the given line magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the input line as a single string. _stack_depth : int If run_line_magic() i
(self, magic_name: str, line: str, _stack_depth=1)
| 2487 | return res |
| 2488 | |
| 2489 | def run_line_magic(self, magic_name: str, line: str, _stack_depth=1): |
| 2490 | """Execute the given line magic. |
| 2491 | |
| 2492 | Parameters |
| 2493 | ---------- |
| 2494 | magic_name : str |
| 2495 | Name of the desired magic function, without '%' prefix. |
| 2496 | line : str |
| 2497 | The rest of the input line as a single string. |
| 2498 | _stack_depth : int |
| 2499 | If run_line_magic() is called from magic() then _stack_depth=2. |
| 2500 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' |
| 2501 | """ |
| 2502 | fn = self._find_with_lazy_load("line", magic_name) |
| 2503 | if fn is None: |
| 2504 | lazy = self.magics_manager.lazy_magics.get(magic_name) |
| 2505 | if lazy: |
| 2506 | self.run_line_magic("load_ext", lazy) |
| 2507 | fn = self.find_line_magic(magic_name) |
| 2508 | if fn is None: |
| 2509 | cm = self.find_cell_magic(magic_name) |
| 2510 | etpl = "Line magic function `%%%s` not found%s." |
| 2511 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
| 2512 | 'did you mean that instead?)' % magic_name ) |
| 2513 | raise UsageError(etpl % (magic_name, extra)) |
| 2514 | else: |
| 2515 | # Note: this is the distance in the stack to the user's frame. |
| 2516 | # This will need to be updated if the internal calling logic gets |
| 2517 | # refactored, or else we'll be expanding the wrong variables. |
| 2518 | |
| 2519 | # Determine stack_depth depending on where run_line_magic() has been called |
| 2520 | stack_depth = _stack_depth |
| 2521 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
| 2522 | # magic has opted out of var_expand |
| 2523 | magic_arg_s = line |
| 2524 | else: |
| 2525 | magic_arg_s = self.var_expand(line, stack_depth) |
| 2526 | # Put magic args in a list so we can call with f(*a) syntax |
| 2527 | args = [magic_arg_s] |
| 2528 | kwargs = {} |
| 2529 | # Grab local namespace if we need it: |
| 2530 | if getattr(fn, "needs_local_scope", False): |
| 2531 | kwargs['local_ns'] = self.get_local_scope(stack_depth) |
| 2532 | with self.builtin_trap: |
| 2533 | result = fn(*args, **kwargs) |
| 2534 | |
| 2535 | # The code below prevents the output from being displayed |
| 2536 | # when using magics with decorator @output_can_be_silenced |
| 2537 | # when the last Python token in the expression is a ';'. |
| 2538 | if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): |
| 2539 | if DisplayHook.semicolon_at_end_of_expression(magic_arg_s): |
| 2540 | return None |
| 2541 | |
| 2542 | return result |
| 2543 | |
| 2544 | def get_local_scope(self, stack_depth): |
| 2545 | """Get local scope at given stack depth. |