2.2 IPython基础

在本节中,我们会教你打开运行IPython shell和jupyter notebook,并介绍一些基本概念。

运行IPython Shell

你可以用ipython在命令行打开IPython Shell,就像打开普通的Python解释器:

  1. $ ipython
  2. Python 3.6.0 | packaged by conda-forge | (default, Jan 13 2017, 23:17:12)
  3. Type "copyright", "credits" or "license" for more information.
  4. IPython 5.1.0 -- An enhanced Interactive Python.
  5. ? -> Introduction and overview of IPython's features.
  6. %quickref -> Quick reference.
  7. help -> Python's own help system.
  8. object? -> Details about 'object', use 'object??' for extra details.
  9. In [1]: a = 5
  10. In [2]: a
  11. Out[2]: 5

你可以通过输入代码并按Return(或Enter),运行任意Python语句。当你只输入一个变量,它会显示代表的对象:

  1. In [5]: import numpy as np
  2. In [6]: data = {i : np.random.randn() for i in range(7)}
  3. In [7]: data
  4. Out[7]:
  5. {0: -0.20470765948471295,
  6. 1: 0.47894333805754824,
  7. 2: -0.5194387150567381,
  8. 3: -0.55573030434749,
  9. 4: 1.9657805725027142,
  10. 5: 1.3934058329729904,
  11. 6: 0.09290787674371767}

前两行是Python代码语句;第二条语句创建一个名为data的变量,它引用一个新创建的Python字典。最后一行打印data的值。

许多Python对象被格式化为更易读的形式,或称作pretty-printed,它与普通的print不同。如果在标准Python解释器中打印上述data变量,则可读性要降低:

  1. >>> from numpy.random import randn
  2. >>> data = {i : randn() for i in range(7)}
  3. >>> print(data)
  4. {0: -1.5948255432744511, 1: 0.10569006472787983, 2: 1.972367135977295,
  5. 3: 0.15455217573074576, 4: -0.24058577449429575, 5: -1.2904897053651216,
  6. 6: 0.3308507317325902}

IPython还支持执行任意代码块(通过一个华丽的复制-粘贴方法)和整段Python脚本的功能。你也可以使用Jupyter notebook运行大代码块,接下来就会看到。

运行Jupyter Notebook

notebook是Jupyter项目的重要组件之一,它是一个代码、文本(有标记或无标记)、数据可视化或其它输出的交互式文档。Jupyter Notebook需要与内核互动,内核是Jupyter与其它编程语言的交互编程协议。Python的Jupyter内核是使用IPython。要启动Jupyter,在命令行中输入jupyter notebook:

  1. $ jupyter notebook
  2. [I 15:20:52.739 NotebookApp] Serving notebooks from local directory:
  3. /home/wesm/code/pydata-book
  4. [I 15:20:52.739 NotebookApp] 0 active kernels
  5. [I 15:20:52.739 NotebookApp] The Jupyter Notebook is running at:
  6. http://localhost:8888/
  7. [I 15:20:52.740 NotebookApp] Use Control-C to stop this server and shut down
  8. all kernels (twice to skip confirmation).
  9. Created new window in existing browser session.

在多数平台上,Jupyter会自动打开默认的浏览器(除非指定了--no-browser)。或者,可以在启动notebook之后,手动打开网页http://localhost:8888/。图2-1展示了Google Chrome中的notebook。

笔记:许多人使用Jupyter作为本地的计算环境,但它也可以部署到服务器上远程访问。这里不做介绍,如果需要的话,鼓励读者自行到网上学习。

图2-1 Jupyter notebook启动页面

要新建一个notebook,点击按钮New,选择“Python3”或“conda[默认项]”。如果是第一次,点击空格,输入一行Python代码。然后按Shift-Enter执行。

图2-2 Jupyter新notebook页面

当保存notebook时(File目录下的Save and Checkpoint),会创建一个后缀名为.ipynb的文件。这是一个自包含文件格式,包含当前笔记本中的所有内容(包括所有已评估的代码输出)。可以被其它Jupyter用户加载和编辑。要加载存在的notebook,把它放到启动notebook进程的相同目录内。你可以用本书的示例代码练习,见图2-3。

虽然Jupyter notebook和IPython shell使用起来不同,本章中几乎所有的命令和工具都可以通用。

图2-3 Jupyter查看一个存在的notebook的页面

Tab补全

从外观上,IPython shell和标准的Python解释器只是看起来不同。IPython shell的进步之一是具备其它IDE和交互计算分析环境都有的tab补全功能。在shell中输入表达式,按下Tab,会搜索已输入变量(对象、函数等等)的命名空间:

  1. In [1]: an_apple = 27
  2. In [2]: an_example = 42
  3. In [3]: an<Tab>
  4. an_apple and an_example any

在这个例子中,IPython呈现出了之前两个定义的变量和Python的关键字和内建的函数any。当然,你也可以补全任何对象的方法和属性:

  1. In [3]: b = [1, 2, 3]
  2. In [4]: b.<Tab>
  3. b.append b.count b.insert b.reverse
  4. b.clear b.extend b.pop b.sort
  5. b.copy b.index b.remove

同样也适用于模块:

  1. In [1]: import datetime
  2. In [2]: datetime.<Tab>
  3. datetime.date datetime.MAXYEAR datetime.timedelta
  4. datetime.datetime datetime.MINYEAR datetime.timezone
  5. datetime.datetime_CAPI datetime.time datetime.tzinfo

在Jupyter notebook和新版的IPython(5.0及以上),自动补全功能是下拉框的形式。

笔记:注意,默认情况下,IPython会隐藏下划线开头的方法和属性,比如魔术方法和内部的“私有”方法和属性,以避免混乱的显示(和让新手迷惑!)这些也可以tab补全,但是你必须首先键入一个下划线才能看到它们。如果你喜欢总是在tab补全中看到这样的方法,你可以IPython配置中进行设置。可以在IPython文档中查找方法。

除了补全命名、对象和模块属性,Tab还可以补全其它的。当输入看似文件路径时(即使是Python字符串),按下Tab也可以补全电脑上对应的文件信息:

  1. In [7]: datasets/movielens/<Tab>
  2. datasets/movielens/movies.dat datasets/movielens/README
  3. datasets/movielens/ratings.dat datasets/movielens/users.dat
  4. In [7]: path = 'datasets/movielens/<Tab>
  5. datasets/movielens/movies.dat datasets/movielens/README
  6. datasets/movielens/ratings.dat datasets/movielens/users.dat

结合%run,tab补全可以节省许多键盘操作。

另外,tab补全可以补全函数的关键词参数(包括等于号=)。见图2-4。

图2-4 Jupyter notebook中自动补全函数关键词

后面会仔细地学习函数。

自省

在变量前后使用问号?,可以显示对象的信息:

  1. In [8]: b = [1, 2, 3]
  2. In [9]: b?
  3. Type: list
  4. String Form:[1, 2, 3]
  5. Length: 3
  6. Docstring:
  7. list() -> new empty list
  8. list(iterable) -> new list initialized from iterable's items
  9. In [10]: print?
  10. Docstring:
  11. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  12. Prints the values to a stream, or to sys.stdout by default.
  13. Optional keyword arguments:
  14. file: a file-like object (stream); defaults to the current sys.stdout.
  15. sep: string inserted between values, default a space.
  16. end: string appended after the last value, default a newline.
  17. flush: whether to forcibly flush the stream.
  18. Type: builtin_function_or_method

这可以作为对象的自省。如果对象是一个函数或实例方法,定义过的文档字符串,也会显示出信息。假设我们写了一个如下的函数:

  1. def add_numbers(a, b):
  2. """
  3. Add two numbers together
  4. Returns
  5. -------
  6. the_sum : type of arguments
  7. """
  8. return a + b

然后使用?符号,就可以显示如下的文档字符串:

  1. In [11]: add_numbers?
  2. Signature: add_numbers(a, b)
  3. Docstring:
  4. Add two numbers together
  5. Returns
  6. -------
  7. the_sum : type of arguments
  8. File: <ipython-input-9-6a548a216e27>
  9. Type: function

使用??会显示函数的源码:

  1. In [12]: add_numbers??
  2. Signature: add_numbers(a, b)
  3. Source:
  4. def add_numbers(a, b):
  5. """
  6. Add two numbers together
  7. Returns
  8. -------
  9. the_sum : type of arguments
  10. """
  11. return a + b
  12. File: <ipython-input-9-6a548a216e27>
  13. Type: function

?还有一个用途,就是像Unix或Windows命令行一样搜索IPython的命名空间。字符与通配符结合可以匹配所有的名字。例如,我们可以获得所有包含load的顶级NumPy命名空间:

  1. In [13]: np.*load*?
  2. np.__loader__
  3. np.load
  4. np.loads
  5. np.loadtxt
  6. np.pkgload

%run命令

你可以用%run命令运行所有的Python程序。假设有一个文件ipython_script_test.py

  1. def f(x, y, z):
  2. return (x + y) / z
  3. a = 5
  4. b = 6
  5. c = 7.5
  6. result = f(a, b, c)

可以如下运行:

  1. In [14]: %run ipython_script_test.py

这段脚本运行在空的命名空间(没有import和其它定义的变量),因此结果和普通的运行方式python script.py相同。文件中所有定义的变量(import、函数和全局变量,除非抛出异常),都可以在IPython shell中随后访问:

  1. In [15]: c
  2. Out [15]: 7.5
  3. In [16]: result
  4. Out[16]: 1.4666666666666666

如果一个Python脚本需要命令行参数(在sys.argv中查找),可以在文件路径之后传递,就像在命令行上运行一样。

笔记:如果想让一个脚本访问IPython已经定义过的变量,可以使用%run -i

在Jupyter notebook中,你也可以使用%load,它将脚本导入到一个代码格中:

  1. >>> %load ipython_script_test.py
  2. def f(x, y, z):
  3. return (x + y) / z
  4. a = 5
  5. b = 6
  6. c = 7.5
  7. result = f(a, b, c)

中断运行的代码

代码运行时按Ctrl-C,无论是%run或长时间运行命令,都会导致KeyboardInterrupt。这会导致几乎所有Python程序立即停止,除非一些特殊情况。

警告:当Python代码调用了一些编译的扩展模块,按Ctrl-C不一定将执行的程序立即停止。在这种情况下,你必须等待,直到控制返回Python解释器,或者在更糟糕的情况下强制终止Python进程。

从剪贴板执行程序

如果使用Jupyter notebook,你可以将代码复制粘贴到任意代码格执行。在IPython shell中也可以从剪贴板执行。假设在其它应用中复制了如下代码:

  1. x = 5
  2. y = 7
  3. if x > 5:
  4. x += 1
  5. y = 8

最简单的方法是使用%paste%cpaste函数。%paste可以直接运行剪贴板中的代码:

  1. In [17]: %paste
  2. x = 5
  3. y = 7
  4. if x > 5:
  5. x += 1
  6. y = 8
  7. ## -- End pasted text --

%cpaste功能类似,但会给出一条提示:

  1. In [18]: %cpaste
  2. Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
  3. :x = 5
  4. :y = 7
  5. :if x > 5:
  6. : x += 1
  7. :
  8. : y = 8
  9. :--

使用%cpaste,你可以粘贴任意多的代码再运行。你可能想在运行前,先看看代码。如果粘贴了错误的代码,可以用Ctrl-C中断。

键盘快捷键

IPython有许多键盘快捷键进行导航提示(类似Emacs文本编辑器或UNIX bash Shell)和交互shell的历史命令。表2-1总结了常见的快捷键。图2-5展示了一部分,如移动光标。

图2-5 IPython shell中一些快捷键的说明

表2-1 IPython的标准快捷键

Jupyter notebooks有另外一套庞大的快捷键。因为它的快捷键比IPython的变化快,建议你参阅Jupyter notebook的帮助文档。

魔术命令

IPython中特殊的命令(Python中没有)被称作“魔术”命令。这些命令可以使普通任务更便捷,更容易控制IPython系统。魔术命令是在指令前添加百分号%前缀。例如,可以用%timeit(这个命令后面会详谈)测量任何Python语句,例如矩阵乘法,的执行时间:

  1. In [20]: a = np.random.randn(100, 100)
  2. In [20]: %timeit np.dot(a, a)
  3. 10000 loops, best of 3: 20.9 µs per loop

魔术命令可以被看做IPython中运行的命令行。许多魔术命令有“命令行”选项,可以通过?查看:

  1. In [21]: %debug?
  2. Docstring:
  3. ::
  4. %debug [--breakpoint FILE:LINE] [statement [statement ...]]
  5. Activate the interactive debugger.
  6. This magic command support two ways of activating debugger.
  7. One is to activate debugger before executing code. This way, you
  8. can set a break point, to step through the code from the point.
  9. You can use this mode by giving statements to execute and optionally
  10. a breakpoint.
  11. The other one is to activate debugger in post-mortem mode. You can
  12. activate this mode simply running %debug without any argument.
  13. If an exception has just occurred, this lets you inspect its stack
  14. frames interactively. Note that this will always work only on the last
  15. traceback that occurred, so you must call this quickly after an
  16. exception that you wish to inspect has fired, because if another one
  17. occurs, it clobbers the previous one.
  18. If you want IPython to automatically do this on every exception, see
  19. the %pdb magic for more details.
  20. positional arguments:
  21. statement Code to run in debugger. You can omit this in cell
  22. magic mode.
  23. optional arguments:
  24. --breakpoint <FILE:LINE>, -b <FILE:LINE>
  25. Set break point at LINE in FILE.

魔术函数默认可以不用百分号,只要没有变量和函数名相同。这个特点被称为“自动魔术”,可以用%automagic打开或关闭。

一些魔术函数与Python函数很像,它的结果可以赋值给一个变量:

  1. In [22]: %pwd
  2. Out[22]: '/home/wesm/code/pydata-book
  3. In [23]: foo = %pwd
  4. In [24]: foo
  5. Out[24]: '/home/wesm/code/pydata-book'

IPython的文档可以在shell中打开,我建议你用%quickref%magic学习下所有特殊命令。表2-2列出了一些可以提高生产率的交互计算和Python开发的IPython指令。

表2-2 一些常用的IPython魔术命令

集成Matplotlib

IPython在分析计算领域能够流行的原因之一是它非常好的集成了数据可视化和其它用户界面库,比如matplotlib。不用担心以前没用过matplotlib,本书后面会详细介绍。%matplotlib魔术函数配置了IPython shell和Jupyter notebook中的matplotlib。这点很重要,其它创建的图不会出现(notebook)或获取session的控制,直到结束(shell)。

在IPython shell中,运行%matplotlib可以进行设置,可以创建多个绘图窗口,而不会干扰控制台session:

  1. In [26]: %matplotlib
  2. Using matplotlib backend: Qt4Agg

在JUpyter中,命令有所不同(图2-6):

  1. In [26]: %matplotlib inline

图2-6 Jupyter行内matplotlib作图