You are viewing an older version (9.3.0). Go to latest (9.13.0)
{ } Raw JSON

bundles / IPython 9.3.0 / IPython / core / magics / execution / ExecutionMagics / macro

function

IPython.core.magics.execution:ExecutionMagics.macro

source: /IPython/core/magics/execution.py :1421

Signature

def   macro ( self parameter_s = '' )

Summary

Define a macro for future re-execution. It accepts ranges of history, filenames or string objects.

Extended Summary

Usage

%macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...

Options:

-r

Use 'raw' input. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed at the command line is used instead.

-q

Quiet macro definition. By default, a tag line is printed to indicate the macro has been created, and then the contents of the macro are printed. If this option is given, then no printout is produced once the macro is created.

This will define a global variable called name which is a string made of joining the slices and lines you specify (n1,n2,... numbers above) from your input history into a single string. This variable acts like an automatic function which re-executes those lines as if you had typed them. You just type 'name' at the prompt and the code executes.

The syntax for indicating input ranges is described in %history.

Note: as a 'hidden' feature, you can also use traditional python slice notation, where N:M means numbers N through M-1.

For example, if your history contains (print using %hist -n )

44: x=1
45: y=3
46: z=x+y
47: print(x)
48: a=5
49: print('x',x,'y',y)

you can create a macro with lines 44 through 47 (included) and line 49 called my_macro with

In [55]: %macro my_macro 44-47 49

Now, typing my_macro (without quotes) will re-execute all this code in one pass.

You don't need to give the line-numbers in order, and any given line number can appear multiple times. You can assemble macros with any lines from your input history in any order.

The macro is a simple object which holds its value in an attribute, but IPython's display system checks for macros and executes them as code instead of printing them when you type their name.

You can view a macro's contents by explicitly printing it with

print(macro_name)

Aliases

  • IPython.core.magics.ExecutionMagics.macro