How to run IPython magic from a script

ipython, python

Solution

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.

Problem

The IPython %timeit magic command does its job well for measuring time required to run some Python code. Now, I want to use something analogous in the Python script. I know about the timeit module, however, it has several disadvantages, for example, how to select the number of runs adaptively? i.e., the default code ``` import timeit t=timeit.Timer("code(f)", "from __main__ import code,f") t.timeit() ``` runs the code million times. The %timeit IPyhton magic command does it automatically. I suggest that I could use something like the MATLAB code http://www.mathworks.com/matlabcentral/fileexchange/18798 that does all the job automatically (and also tells if the overhead of the function is large). How can I call %timeit magic from a Python script (or maybe there is a better timing solution) ?

Original source

Related problems