The text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!
之前两个章节介绍了 IPython 中一些快速使用 Python 的便捷操作。这章节我们介绍一些在此基础上 IPython 的一些额外的命令,这些命令被称作 IPython 的魔法命令,它们前面都有一个 %
。这些命令用于数据分析中经常用到的操作。魔法命令分为两种,一种是单行魔法命令,它们以一个 %
开始并只处理单行输入。另一种是块魔法命令,它们以 %%
开始,处理多行输入。下面我们先介绍几个简单的例子,然后再去了解哪些最常用的情况。
The previous two sections showed how IPython lets you use and explore Python efficiently and interactively.
Here we'll begin discussing some of the enhancements that IPython adds on top of the normal Python syntax.
These are known in IPython as magic commands, and are prefixed by the %
character.
These magic commands are designed to succinctly solve various common problems in standard data analysis.
Magic commands come in two flavors: line magics, which are denoted by a single %
prefix and operate on a single line of input, and cell magics, which are denoted by a double %%
prefix and operate on multiple lines of input.
We'll demonstrate and discuss a few brief examples here, and come back to more focused discussion of several useful magic commands later in the chapter.
%paste
%cpaste
粘贴代码¶%paste
and %cpaste
¶在 IPython 中粘贴代码经常会因为缩进或者解释器标记导致报错。例如下面这样一个例子,当你在一个网站找到一段代码想要把它粘贴到你的解释器的时候:
When working in the IPython interpreter, one common gotcha is that pasting multi-line code blocks can lead to unexpected errors, especially when indentation and interpreter markers are involved. A common case is that you find some example code on a website and want to paste it into your interpreter. Consider the following simple function:
>>> def donothing(x):
... return x
代码的格式与它在 Python 解释器中的格式相同,如果将它直接复制粘贴到 IPython 中,您会收到一个错误:
The code is formatted as it would appear in the Python interpreter, and if you copy and paste this directly into IPython you get an error:
In [2]: >>> def donothing(x):
...: ... return x
...:
File "<ipython-input-20-5a66c8964687>", line 2
... return x
^
SyntaxError: invalid syntax
如果直接粘贴解释器被额外的提示符影响,但不要担心 -- IPython 的 %paste
魔法函数旨在处理这种含提示符的多行输入的情况:
In the direct paste, the interpreter is confused by the additional prompt characters.
But never fear–IPython's %paste
magic function is designed to handle this exact type of multi-line, marked-up input:
In [3]: %paste
>>> def donothing(x):
... return x
## -- End pasted text --
%paste
命令会输入并直接执行这行命令,所以这个函数已经可以被调用了:
The %paste
command both enters and executes the code, so now the function is ready to be used:
In [4]: donothing(10)
Out[4]: 10
另一个目的类似的命令是 %cpaste
它会创建一个多行输入的区域让你可以粘贴代码并一起执行:
A command with a similar intent is %cpaste
, which opens up an interactive multiline prompt in which you can paste one or more chunks of code to be executed in a batch:
In [5]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:>>> def donothing(x):
:... return x
:--
这些魔法命令提供的功能在标准的 IPython 解释器里面就很难做到了。
These magic commands, like others we'll see, make available functionality that would be difficult or impossible in a standard Python interpreter.
%run
执行外部代码¶%run
¶当你的代码越来越多,你可能希望自己可以一方面在 IPython 中做一些探索性的尝试又能把重用的代码保存在文件中。通过 %run
命令你就可以在 IPython 中直接运行一个文件了,免去了去另一个窗口单独执行它的麻烦。
As you begin developing more extensive code, you will likely find yourself working in both IPython for interactive exploration, as well as a text editor to store code that you want to reuse.
Rather than running this code in a new window, it can be convenient to run it within your IPython session.
This can be done with the %run
magic.
比如你有一个 myscript.py
的文件:
For example, imagine you've created a myscript.py
file with the following contents:
#-------------------------------------
# file: myscript.py
def square(x):
"""square a number"""
return x ** 2
for N in range(1, 4):
print(N, "squared is", square(N))
你可以用下面的方法在 IPython 里面执行它:
You can execute this from your IPython session as follows:
In [6]: %run myscript.py
1 squared is 1
2 squared is 4
3 squared is 9
在执行之后,文件中定义的函数就能在当前的回话里调用了:
Note also that after you've run this script, any functions defined within it are available for use in your IPython session:
In [7]: square(5)
Out[7]: 25
%run
命令还包含一些参数可以让你决定怎么执行你的文件,这些信息都在它的文档里,在 IPython 中键入 %run?
就能看到了。
There are several options to fine-tune how your code is run; you can see the documentation in the normal way, by typing %run?
in the IPython interpreter.
%timeit
对代码执行计时¶%timeit
¶另一个常用的魔法命令是 %timeit
它对 Python 语句计时。下面的例子可以看到一个 list comprehension 的执行速度如何:
Another example of a useful magic function is %timeit
, which will automatically determine the execution time of the single-line Python statement that follows it.
For example, we may want to check the performance of a list comprehension:
In [8]: %timeit L = [n ** 2 for n in range(1000)]
1000 loops, best of 3: 325 µs per loop
%timeit
还有一个好处就是它可以自动对一个简单的语句多次执行来获取一个更稳定的运行时间。如果想要对多行语句计时,只需在其前面再添加一个 %
将其变为块魔法命令即可。例如下面是一个和上面语法等价的 for
循环版本:
The benefit of %timeit
is that for short commands it will automatically perform multiple runs in order to attain more robust results.
For multi line statements, adding a second %
sign will turn this into a cell magic that can handle multiple lines of input.
For example, here's the equivalent construction with a for
-loop:
In [9]: %%timeit
...: L = []
...: for n in range(1000):
...: L.append(n ** 2)
...:
1000 loops, best of 3: 373 µs per loop
可以看到在这里 list comprehensions 比 for
循环快了大约 10%。我们会在性能调优与计时对 %timeit
和其他调优方法做更多的介绍。
We can immediately see that list comprehensions are about 10% faster than the equivalent for
-loop construction in this case.
We'll explore %timeit
and other approaches to timing and profiling code in Profiling and Timing Code.
?
、%magic
与 %lsmagic
¶?
, %magic
, and %lsmagic
¶像普通的 Python 函数一样,IPython 魔法命令也有 docstrings,这个文档可以以标准方式访问。例如阅读 %timeit
的文档只需键入:
Like normal Python functions, IPython magic functions have docstrings, and this useful
documentation can be accessed in the standard manner.
So, for example, to read the documentation of the %timeit
magic simply type this:
In [10]: %timeit?
用同样的方式也可以访问其他功能的文档。要访问所有魔法函数的一般说明(包括一些示例),您可以键入:
Documentation for other functions can be accessed similarly. To access a general description of available magic functions, including some examples, you can type this:
In [11]: %magic
想要罗列多有
For a quick and simple list of all available magic functions, type this:
In [12]: %lsmagic
Finally, I'll mention that it is quite straightforward to define your own magic functions if you wish. We won't discuss it here, but if you are interested, see the references listed in More IPython Resources.