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

    你可以通过输入代码并按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。

    要新建一个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使用起来不同,本章中几乎所有的命令和工具都可以通用。

    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

    除了补全命名、对象和模块属性,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. datasets/movielens/movies.dat datasets/movielens/README
    5. datasets/movielens/ratings.dat datasets/movielens/users.dat

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

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

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

    后面会仔细地学习函数。

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

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

    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中查找),可以在文件路径之后传递,就像在命令行上运行一样。

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

    中断运行的代码

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

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

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

    1. In [17]: %paste
    2. x = 5
    3. if x > 5:
    4. x += 1
    5. y = 8
    6. ## -- 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-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指令。

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

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

    1. Using matplotlib backend: Qt4Agg

    图2-6 Jupyter行内matplotlib作图