Jupyter 简明教程
IPython - Magic Commands
与标准 Python 外壳相比,魔术命令或魔术函数是 IPython 提供的重要增强功能之一。这些魔术命令旨在使用 Python 来解决数据分析中的常见问题。事实上,它们控制着 IPython 本身的行为。
Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself.
当 Python 语法不是最自然时,魔术命令可作为方便的功能。它们可用于在其工作流程中嵌入无效 Python 语法。
Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow.
Types of Magic Commands
魔术命令有两种类型 −
There are two types of magic commands −
-
Line magics
-
Cell magics
Line Magics
它们类似于命令行调用。它们以 % 字符开头。该行的其余部分是其在没有括号或引号的情况下传递的参数。行魔术可作为表达式使用,其返回值可被分配给变量。
They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes. Line magics can be used as expression and their return value can be assigned to variable.
Cell Magics
它们有一个 %% 字符前缀。与行魔术函数不同,它们可以在其调用下方的多行中操作。事实上,它们可以对其接收的输入进行任意修改,而输入甚至不必是有效的 Python 代码。它们将整个块作为单个字符串接收。
They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string.
要了解有关魔术函数、内置魔术及其文档字符串的更多信息,请使用魔术命令。特定魔术函数的信息可通过 % magicfunction? 命令获取。让我们现在描述一些内置行和单元格魔术命令。
To know more about magic functions, the built-in magics and their docstrings, use the magic command. Information of a specific magic function is obtained by %magicfunction? Command. Let us now describe some of the built-in line and cell magic commands.
Built-in line magics
%autocall [mode]
此魔术函数可以自动调用函数,而无需使用括号。它需要三个可能的模式参数: 0 (off), 1 (smart) is default 或 2 (always on) 。
This magic function makes a function automatically callable without having to use parentheses. It takes three possible mode parameters: 0 (off), 1 (smart) is default or 2 (always on).

%automagic
如果设置为 1,则魔术函数在无需输入初始 % 的情况下可变为可调用。没有参数时,它会切换开/关。要停用,请设置为 0。
Magic functions are callable without having to type the initial % if set to 1. Without arguments it toggles on/off. To deactivate, set to 0.
以下示例显示了在将 %automagic 设置为 1 时,调用了不带前导 % 的魔术函数 %pwd (显示当前工作目录)
The following example shows a magic function %pwd (displays present working directory) being called without leading % when %automagic set to 1

%cd
该行魔术改变了当前目录。该命令会在 IPython 会话期间自动维护您访问的一个内部目录列表,并在变量 _dh 中。您还可以执行 ‘cd -<tab>’ 来方便地查看目录历史记录。
This line magic changes the current directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. You can also do ‘cd -<tab>’ to see directory history conveniently.

Usage
%cd 命令可以用以下方式使用 −
The %cd command can be used in the following ways −
-
%cd <dir> − Changes current working directory to <dir>
-
%cd.. − Changes current directory to parent directory
-
%cd − changes to last visited directory.
%dhist
该魔术命令会打印您在当前会话中访问过的所有目录。每当使用 %cd 命令时,此列表都会在 _dh 变量中更新。
This magic command prints all directories you have visited in current session. Every time %cd command is used, this list is updated in _dh variable.

%edit
该魔术命令会调用当前操作系统(Windows 的记事本)的默认文本编辑器来编辑 Python 脚本。脚本在关闭编辑器后执行。
This magic command calls upon the default text editor of current operating system (Notepad for Windows) for editing a Python script. The script is executed as the editor is closed.
%env
该魔术命令将列出所有环境变量。它还会读取特定变量的值或设置环境变量的值。
This magic command will list all environment variables. It also reads value of particular variable or set the value of environment variable.
Usage
Usage
%cd 命令可以用以下方式使用 −
The %cd command can be used in the following ways −
-
%env − Lists all environment variables
-
%env var − Gets value for var
-
%env var val − Sets value for var

%gui [GUINAME]
当不带参数使用该命令时,它将启用或禁用 IPython GUI 事件循环集成。通过 GUINAME 参数,该魔术可以将默认 GUI 工具包替换为指定的一个。
When used without argument this command enables or disables IPython GUI event loop integration. With GUINAME argument, this magic replaces the default GUI toolkits by the specified one.
Sr.No. |
Command & Description |
1 |
%gui wx enable wxPython event loop integration |
2 |
*%gui qt4 |
qt* enable PyQt4 event loop integration |
3 |
%gui qt5 enable PyQt5 event loop integration |
4 |
%gui gtk enable PyGTK event loop integration |
5 |
%gui gtk3 enable Gtk3 event loop integration |
6 |
%gui tk enable Tk event loop integration |
7 |
%gui osx enable Cocoa event loop integration |
8 |
(requires %matplotlib 1.1) |
9 |
%matplotlib
此函数在 IPython 会话中激活 Matplotlib 交互式支持。但是,它不会导入 Matplotlib 库。Matplotlib 默认 GUI 工具包是 TkAgg。但您可以显式请求不同的 GUI 后端。您可以看到可用后端的列表,如下所示 −
This function activates matplotlib interactive support during an IPython session. However, it does not import matplotlib library. The matplotlib default GUI toolkit is TkAgg. But you can explicitly request a different GUI backend. You can see a list of the available backends as shown −
In [4]: %matplotlib --list
Available matplotlib backends:
['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg','gtk', 'tk', 'inline']
此处所示的 IPython 会话使用 qt 工具包绘制正弦波 −
The IPython session shown here plots a sine wave using qt toolkit −

在使用 Jupyter notebook 时,%matplotlib inline 指令仅在浏览器中显示绘图输出。
While using Jupyter notebook, %matplotlib inline directive displays plot output in the browser only.
%notebook
此函数将当前 IPython 历史记录转换为具有 ipynb 扩展名的 IPython notebook 文件。上一个示例中的输入单元格保存为 sine.ipynb
This function converts current IPython history into an IPython notebook file with ipynb extension. The input cells in previous example are saved as sine.ipynb
%notebook sine.ipynb
%pinfo
此函数类似于对象自省 ? 字符。要获取有关对象的的信息,请使用以下命令 −
This function is similar to object introspection ? character. To obtain information about an object, use the following command −
%pinfo object
这与 object? 或 ?object 同义。
This is synonymous to object? or ?object.
%precision
此魔术函数将浮点结果限制为十进制小数后的指定位数。
This magic function restricts a floating point result to specified digits after decimal.

%pylab
此函数用 Matplotlib 和 numpy 库填充当前 IPython 会话。
This function populates current IPython session with matplotlib, and numpy libraries.

%recall
在不带任何参数的情况下执行时,此函数执行上一个命令。
When executed without any parameter, this function executes previous command.
请注意,在 %recall n 中,前面的数字是输入单元格编号。因此,单元格 n 中的命令被调用。您可以通过使用诸如 %recall 1-4 之类的命令来调用部分单元格中的命令。当前输入单元格由调用的单元格填充,并且光标闪烁,直至按下回车键。
Note that in %recall n, number in front of it is input cell number. Hence the command in the nth cell is recalled. You can recall commands in section of cells by using command such as %recall 1-4. Current input cell is populated with recalled cell and the cursor blinks till the enter key is pressed.

%time
此命令显示 IPython 环境执行 Python 表达式所需的时间。
This command displays time required by IPython environment to execute a Python expression.

%timeit
此函数还显示 IPython 环境执行 Python 表达式所需的时间。Python 语句或表达式的执行时间使用 timeit 模块。此函数可同时用作行魔术和单元格魔术,如下所述 −
This function also displays time required by IPython environment to execute a Python expression. Time execution of a Python statement or expression uses the timeit module. This function can be used both as a line and cell magic as explained here −
-
In line mode you can time a single-line.
-
In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code.