How to run IPython magic from a script

It depends on which version of IPython you have. If you have 1.x:

from IPython import get_ipython
ipython = get_ipython()

If you have an older version:

import IPython.core.ipapi  
ipython = IPython.core.ipapi.get()

or

import IPython.ipapi  
ipython = IPython.ipapi.get()

Once that’s done, run a magic command like this:

ipython.magic("timeit abs(-42)")

Note: The script must be run via ipython.

See Line magics

magic(...) is deprecated since IPython 0.13, use run_line_magic(magic_name, parameter_s)

ipython.run_line_magic("timeit", "abs(-42)")
run_line_magic(magic_name: str, line, _stack_depth=1) method of ipykernel.zmqshell.ZMQInteractiveShell instance
    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() is called from magic() then _stack_depth=2.
        This is added to ensure backward compatibility for use of 'get_ipython().magic()'

Also see ipython.run_cell_magic and Cell magics

run_cell_magic(magic_name, line, cell) method of ipykernel.zmqshell.ZMQInteractiveShell instance
    Execute the given cell magic.
    
    Parameters
    ----------
    magic_name : str
        Name of the desired magic function, without '%' prefix.
    line : str
        The rest of the first input line as a single string.
    cell : str
        The body of the cell as a (possibly multiline) string.

Leave a Comment