内置线条和单元格魔法

名字以一个%开头的魔术以该线的其余部分作为参数,被称为线魔法。以双百分号%%开头的魔术采用多线论证,被称为单元格魔法

一个常用的魔法是 %timeit ,它是 Python 的 timeit.timeit 函数的包装器,用于测量一段代码的执行时间。

In [35]: ra = [random.randint(0,1000) for r in range(1000)]
In [35]: %timeit sorted(ra)
1000 loops, best of 3: 507 µs per loop

单元格魔法的一个例子是%%bash(相当于%%script bash),用于将输入作为 bash 代码运行

In [49]: %%bash
    ...: i=3
    ...: while [ $i -ge 0 ]
    ...: do
    ...: echo $i
    ...: i=$(($i-1))
    ...: done
    ...:
3
2
1
0

请注意,单元格的末尾用空行标记。

要查看所有内置魔法,请使用%lsmagic

In [51]: %lsmagic
Out[51]:
Available line magics:
%alias  %alias_magic  %autocall  %autoindent  %automagic  %bookmark  %cd  %cls
%colors  %config  %copy  %cpaste  %ddir  %debug  %dhist  %dirs  %doctest_mode  
%echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %load  
%load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic
%macro  %magic  %matplotlib  %mkdir  %notebook  %page  %paste  %pastebin  %pdb
%pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  
%prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %quickref  %recall  
%rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  
%save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  
%unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  
%%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  
%%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

请注意,默认情况下,‘automagic’处于启用状态,因此可以在没有%前缀的情况下调用行魔法(但是单元格函数仍然需要%%前缀)。