简介
如果咱们想要运行Python,通常有两种形式,第一种形式就是在Python或者IPython的解释器环境中进行交互式运行,还有一种形式就是程序员最喜爱的编写.py文件,在文件中编写python代码,而后运行。
如果咱们想写一篇对于Python的文章,文章外面有代码,还心愿代码可能在以后页面运行,可不可以做到呢?
能够的,那就是应用咱们明天要介绍的Jupyter Notebook。
Jupyter Notebook
Jupyter我的项目是从Ipython我的项目中分进来的,在Ipython3.x之前,他们两个是在一起公布的。在Ipython4.x之后,Jupyter作为一个独自的我的项目进行开发和治理。因为Jupyter不仅仅能够运行Python程序,它还能够执行其余流程编程语言的运行。
Jupyter Notebook包含三个局部,第一个局部是一个web应用程序,提供交互式界面,能够在交互式界面中运行相应的代码。
上图是NoteBook的交互界面,咱们能够对文档进行编辑,运行等操作。
次要的性能如下:
- 在浏览器中进行代码编辑,主动语法突出显示,缩进和制表符实现/自检性能。
- 从浏览器执行代码的能力,并将计算结果附加到生成它们的代码上。
- 应用诸如HTML,LaTeX,PNG,SVG等富媒体示意来显示计算结果。例如,能够内嵌蕴含matplotlib库渲染的具备出版品质的图形。
- 应用Markdown标记语言在浏览器中对富文本进行的编辑(能够为代码提供正文)不仅限于纯文本。
- 应用LaTeX轻松在markdown单元中蕴含数学符号的能力,并由MathJax本地出现。
第二个局部就是NoteBook的文档了,这个文档存储了要运行的代码和一些形容信息。个别这个文档是以.ipynb的后缀进行存储的。
notebook文档是以json的模式存储的,并用base64进行编码。应用json的益处就是能够在不同的服务器中不便的进行数据的交互。
Notebook documents中除了可运行的代码文件,还能够存储阐明等解释性内容,从而将代码和解释内容完满联合,尤其适宜做学习笔记应用。
笔记本能够通过nbconvert命令导出为多种动态格局,包含HTML,reStructuredText,LaTeX,PDF等多种格局。
另外文档还能够不便的在网络上进行共享。
第三个局部就是代码运行的外围Kernels,通过不同的Kernels搭配,notebook能够反对运行多种程序。比方:Python,java,go,R,ruby,nodejs等等。
这些Kernels和notebook之间是以Json的模式通过MQ来进行通信的。
启动notebook server
有了文档之后,如果咱们想要运行文档,须要启动notebook server。
<code class="shell">jupyter notebook
默认状况下会开启上面的URL: http://127.0.0.1:8888
启动的时候还可指定要关上的.ipynb文件:
<code class="shell">jupyter notebook my_notebook.ipynb
具体的notebook界面的操作这里就不多介绍了,基本上和一般的编译器差不多。大家能够自行摸索。
notebook document 的构造
notebook中蕴含了多个cells,每个cell中蕴含了多行文本输出字段,能够通过Shift-Enter 或者工具栏中的播放按钮来执行其中的代码。
这里的cell有三种类型,别离是code cells,markdown cells和raw cells。
code cells
代码单元容许您编辑和编写新代码,并突出显示残缺的语法和制表符。 您应用的编程语言取决于内核,默认内核(IPython)运行Python代码。
执行代码单元时,它蕴含的代码将发送到与笔记本关联的内核。 而后,从该计算返回的后果将在笔记本中显示为单元格的输入。 输入不仅限于文本,还有许多其余可能的输入模式,包含matplotlib图形和HTML表格(例如,在pandas数据分析包中应用的表格)。
咱们看一个code cells的例子:
#%% import numpy as np my_arr = np.arange(1000000) my_list = list(range(1000000))
每个单元格是以 #%%
来进行分隔的。
Ipython自身还反对多种富文本的展现格局,包含HTML,JSON,PNG,JPEG,SVG,LaTeX等。
Ipython提供了一个display办法,咱们能够应用display来展现要出现的对象:
from IPython.display import display
display(obj)
将会寻找这个对象所有可能的展现类型,并从中筛选一个最适宜的类型进行展现,并将后果存储在Notebook文档外面。
如果你想展现特定类型的对象,那么能够这样:
from IPython.display import ( display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg )
举个展现图片的例子:
from IPython.display import Image i = Image(filename='../images/ipython_logo.png') i display(i)
下面的例子中i蕴含了一个Image对象,间接调用i即可展现,咱们也能够显示的调用display(i)
。
其余的富文本类型能够参考Image,应用办法都是相似的。
markdown cells
markdown是一种简介的标记语言,应用起来非常简单,应用范畴十分宽泛,所以notebook document也反对markdown的语法。
先看一个markdown cell的例子:
#%% md
$ python
Python 3.6.0 | packaged by conda-forge | (default, Jan 13 2017, 23:17:12)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
a = 5
print(a)
5
markdown中的语法在notebook中都是能够用的。
还反对规范的LaTeX 和 AMS-LaTeX语法。
raw cells
原始单元格提供了一个能够间接写入输入的地位。 notebook不会对原始单元格中的内容进行计算。
以模块的模式导入Jupyter Notebooks
有时候咱们心愿以模块的模式导入Jupyter Notebooks,然而惋惜的是,Jupyter Notebooks并不是一个规范的python程序,不过Python提供了一些钩子程序,让咱们可能不便的进行导入。
首先,咱们须要导入一些根本的API :
import io, os, sys, types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell
接下来须要注册NotebookFinder到sys.meta_path:
<code class="Python">sys.meta_path.append(NotebookFinder())
这个NotebookFinder就是定义的钩子。
咱们看下NotebookFinder的定义:
class NotebookFinder(object): """Module finder that locates Jupyter Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key]
外面应用了两个重要的办法,find_notebook用来找到notebook,和NotebookLoader,用来加载notebook。
看下find_notebook的定义:
def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path
看下NotebookLoader的定义:
class NotebookLoader(object): """Module Loader for Jupyter Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__['get_ipython'] = get_ipython sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod
有了他们,咱们就能够间接import咱们本人编写的notebook了。
本文已收录于 http://www.flydean.com/12-jupyter-notebook/
最艰深的解读,最粗浅的干货,最简洁的教程,泛滥你不晓得的小技巧等你来发现!
欢迎关注搞代码gaodaima网的公众号:「程序那些事」,懂技术,更懂你!