第2章 Jupyter Notebooks

自省(introspection)的定义:检查某些事物以确定它是什么、它知道什么以及它能做什么,用于实现在程序运行时获取未知对象的信息。

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

In [8]: b = [1, 2, 3]
In [9]: b?
Type:       list
String Form:[1, 2, 3]
Length:     3
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable's items

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

def add_numbers(a, b):
    """
    Add two numbers together

    Returns
    -------
    the_sum : type of arguments
    """
    return a + b

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

In [11]: add_numbers?
Signature: add_numbers(a, b)
Docstring:
Add two numbers together

Returns
-------
the_sum : type of arguments
File:      <ipython-input-9-6a548a216e27>
Type:      function

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

In [12]: add_numbers??
Signature: add_numbers(a, b)
Source:
def add_numbers(a, b):
    """
    Add two numbers together

    Returns
    -------
    the_sum : type of arguments
    """
    return a + b
File:      <ipython-input-9-6a548a216e27>
Type:      function

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

In [13]: np.*load*?
np.__loader__
np.load
np.loads
np.loadtxt
np.pkgload

%run命令

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

def f(x, y, z):
    return (x + y) / z

a = 5
b = 6
c = 7.5

result = f(a, b, c)

可以如下运行:

%run ipython_script_test.py

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

In [15]: c
Out [15]: 7.5

In [16]: result
Out[16]: 1.4666666666666666

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

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

>>> %load ipython_script_test.py

    def f(x, y, z):
        return (x + y) / z
    a = 5
    b = 6
    c = 7.5

    result = f(a, b, c)

从剪贴板执行程序

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

x = 5
y = 7
if x > 5:
    x += 1 y = 8 

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

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

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

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

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

猜你喜欢

转载自www.cnblogs.com/wjw2018/p/10782707.html