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_mag
(self, magic_name, line, _stack_depth=1)
| 2283 | magic_kind=magic_kind, magic_name=magic_name) |
| 2284 | |
| 2285 | def run_line_magic(self, magic_name, line, _stack_depth=1): |
| 2286 | """Execute the given line magic. |
| 2287 | |
| 2288 | Parameters |
| 2289 | ---------- |
| 2290 | magic_name : str |
| 2291 | Name of the desired magic function, without '%' prefix. |
| 2292 | |
| 2293 | line : str |
| 2294 | The rest of the input line as a single string. |
| 2295 | |
| 2296 | _stack_depth : int |
| 2297 | If run_line_magic() is called from magic() then _stack_depth=2. |
| 2298 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' |
| 2299 | """ |
| 2300 | fn = self.find_line_magic(magic_name) |
| 2301 | if fn is None: |
| 2302 | cm = self.find_cell_magic(magic_name) |
| 2303 | etpl = "Line magic function `%%%s` not found%s." |
| 2304 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
| 2305 | 'did you mean that instead?)' % magic_name ) |
| 2306 | raise UsageError(etpl % (magic_name, extra)) |
| 2307 | else: |
| 2308 | # Note: this is the distance in the stack to the user's frame. |
| 2309 | # This will need to be updated if the internal calling logic gets |
| 2310 | # refactored, or else we'll be expanding the wrong variables. |
| 2311 | |
| 2312 | # Determine stack_depth depending on where run_line_magic() has been called |
| 2313 | stack_depth = _stack_depth |
| 2314 | if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): |
| 2315 | # magic has opted out of var_expand |
| 2316 | magic_arg_s = line |
| 2317 | else: |
| 2318 | magic_arg_s = self.var_expand(line, stack_depth) |
| 2319 | # Put magic args in a list so we can call with f(*a) syntax |
| 2320 | args = [magic_arg_s] |
| 2321 | kwargs = {} |
| 2322 | # Grab local namespace if we need it: |
| 2323 | if getattr(fn, "needs_local_scope", False): |
| 2324 | kwargs['local_ns'] = self.get_local_scope(stack_depth) |
| 2325 | with self.builtin_trap: |
| 2326 | result = fn(*args, **kwargs) |
| 2327 | return result |
| 2328 | |
| 2329 | def get_local_scope(self, stack_depth): |
| 2330 | """Get local scope at given stack depth. |