CodeWalk

Jupyter魔术命令:%与%%的区别及自定义魔法

作者:古法程序员 · 2026-05-30 12:55

请解释Jupyter/IPython中行魔术命令(%)和细胞魔术命令(%%)的区别。列举至少8个最常用的内置魔术命令及其用途(%timeit/%run/%load/%who/%debug/%pdb/%matplotlib/%env/%config)。如何用%run%load%store进行代码复用和数据持久化?如何创建自定义魔术命令(IPython.core.magic)?

回答

古法程序员

行魔术 % vs 细胞魔术 %%

  • %timeit x = [i**2 for i in range(100)] — 作用于本行
  • %%timeit — 作用于整个单元格(需写在第一行)
  • %%bash / %%python / %%writefile — 细胞魔术运行其他语言或写入文件

常用魔术命令

%timeit sum(range(10**6))        # 计时
%run myscript.py                 # 运行Python脚本(可用-n参数传入命名空间)
%load http://example.com/code.py # 从URL加载代码到单元格
%who / %whos                     # 列出当前命名空间中的变量
%debug                           # 进入事后调试器(最后异常处)
%pdb on/off                      # 异常自动进入pdb
%matplotlib inline               # 内嵌绘图(Jupyter默认)
%matplotlib widget               # 交互式绘图(需ipympl)
%env PATH                        # 查看或设置环境变量
%config InlineBackend.figure_format = 'retina'  # 高DPI图
%reset                           # 清除所有变量
%history                         # 查看命令历史
%store var_name                  # 跨notebook持久化变量(pickle存储)
%lprun func_name                 # 逐行性能分析(需line_profiler)

自定义魔术

from IPython.core.magic import register_line_magic

@register_line_magic
def hello(line):
    print(f"Hello, {line}!")

# 使用:%hello World → Hello, World!

细胞魔术

from IPython.core.magic import register_cell_magic

@register_cell_magic
def pandas_info(line, cell):
    import pandas as pd
    df = eval(cell, globals())
    info = df.info() if hasattr(df, 'info') else 'Not a DataFrame'
    print(info)
    return df

最佳实践

  • %history -f script.py 导出为脚本
  • %load_ext autoreload; %autoreload 2 自动重载修改的模块
  • %config ZMQInteractiveShell.ast_node_interactivity='all' 显示所有表达式结果