Magics are special functions that are useful in the context of interactive sessions. They can create or show files, recover commands from history etc. More on magics in the IPython docs.
Before we dig into more magics. Some Python code for a warmup:
print("Xeus(tm) inside!")
a = 2+2
print(a)
def foo(): pass
Line magics start with a single percent (%
) sign. For example, to show current directory.
%pwd
They can also take arguments:
%cd ..
and their result can be assigned to a variable:
current_path = %pwd
print(current_path)
Cell magics start with double percent sign (%%
). Like line magics they can take arguments, but also they use the content of the cell below:
%%writefile test.txt
This will create a new file.
With the text that you see here.
You can also call shell commands by prefixing them with an exclamation mark (!
). For example, unix cat
command displays content of a file.
!cat test.txt
You can also define your own (line or cell) magics:
from IPython.core.magic import (
register_line_magic, register_cell_magic)
@register_line_magic
def lmagic(line):
return line
@register_cell_magic
def cmagic(line, body):
return line + body
%lmagic me
%%cmagic me
hello
You can also install and load magics from elsewhere:
!pip install example_magic
%load_ext example_magic
%abra Helo
To show the list of available magics and some description, use %magic
magic:
%magic
%history
¶show all executed commands
%history
show last two commands
%history -l 2
search for commands containing print
%history -g print
%recall
¶%recall
magic inserts a new cell with a command from history
%recall 2
a = 2+2
%rerun
¶%rerun
repeats the execution of the command
%rerun 3
%timeit
¶%timeit
measures execution time, it can be both line and cell magics
import time
%%timeit
time.sleep(0.1)
%timeit 2+2
?function
or function?
shows docstring for a function or object. It can be at any line in the cell. In a classic notebook it opens a pager at the bottom of the window.
print("hello world")
?print