科技改變生活 · 科技引領(lǐng)未來(lái)
如果我們想要運(yùn)行Python,通常有兩種方式,第一種方式就是在Python或者IPython的解釋器環(huán)境中進(jìn)行交互式運(yùn)行,還有一種方式就是程序員最喜歡的編寫(xiě).py文件,在文件中編寫(xiě)python代碼,然后運(yùn)行。
如果我們想寫(xiě)一篇關(guān)于Python的文章,文章里面有代碼,還希望代碼能夠在當(dāng)前頁(yè)面運(yùn)行,可不可以做到呢?
可以的,那就是使用我們今天要介紹的Jupyter Notebook。
Jupyter項(xiàng)目是從Ipython項(xiàng)目中分出去的,在Ipython3.x之前,他們兩個(gè)是在一起發(fā)布的。在Ipython4.x之后,Jupyter作為一個(gè)單獨(dú)的項(xiàng)目進(jìn)行開(kāi)發(fā)和管理。因?yàn)镴upyter不僅僅可以運(yùn)行Python程序,它還可以執(zhí)行其他流程編程語(yǔ)言的運(yùn)行。
Jupyter Notebook包括三個(gè)部分,第一個(gè)部分是一個(gè)web應(yīng)用程序,提供交互式界面,可以在交互式界面中運(yùn)行相應(yīng)的代碼。
上圖是NoteBook的交互界面,我們可以對(duì)文檔進(jìn)行編輯,運(yùn)行等操作。
主要的功能如下:
第二個(gè)部分就是NoteBook的文檔了,這個(gè)文檔存儲(chǔ)了要運(yùn)行的代碼和一些描述信息。一般這個(gè)文檔是以.ipynb的后綴進(jìn)行存儲(chǔ)的。
notebook文檔是以json的形式存儲(chǔ)的,并用base64進(jìn)行編碼。使用json的好處就是可以在不同的服務(wù)器中方便的進(jìn)行數(shù)據(jù)的交互。
Notebook documents中除了可運(yùn)行的代碼文件,還可以存儲(chǔ)說(shuō)明等解釋性內(nèi)容,從而將代碼和解釋內(nèi)容完美結(jié)合,尤其適合做學(xué)習(xí)筆記使用。
筆記本可以通過(guò)nbconvert命令導(dǎo)出為多種靜態(tài)格式,包括HTML,reStructuredText,LaTeX,PDF等多種格式。
另外文檔還可以方便的在網(wǎng)絡(luò)上進(jìn)行共享。
第三個(gè)部分就是代碼運(yùn)行的核心Kernels,通過(guò)不同的Kernels搭配,notebook可以支持運(yùn)行多種程序。比如:Python,java,go,R,ruby,nodejs等等。
這些Kernels和notebook之間是以Json的形式通過(guò)MQ來(lái)進(jìn)行通信的。
有了文檔之后,如果我們想要運(yùn)行文檔,需要啟動(dòng)notebook server。
jupyter notebook
默認(rèn)情況下會(huì)開(kāi)啟下面的URL: :8888
啟動(dòng)的時(shí)候還可指定要打開(kāi)的.ipynb文件:
jupyter notebook my_notebook.ipynb
具體的notebook界面的操作這里就不多介紹了,基本上和普通的編譯器差不多。大家可以自行探索。
notebook中包含了多個(gè)cells,每個(gè)cell中包含了多行文本輸入字段,可以通過(guò)Shift-Enter 或者工具欄中的播放按鈕來(lái)執(zhí)行其中的代碼。
這里的cell有三種類型,分別是code cells,markdown cells和raw cells。
代碼單元允許您編輯和編寫(xiě)新代碼,并突出顯示完整的語(yǔ)法和制表符。 您使用的編程語(yǔ)言取決于內(nèi)核,默認(rèn)內(nèi)核(IPython)運(yùn)行Python代碼。
執(zhí)行代碼單元時(shí),它包含的代碼將發(fā)送到與筆記本關(guān)聯(lián)的內(nèi)核。 然后,從該計(jì)算返回的結(jié)果將在筆記本中顯示為單元格的輸出。 輸出不僅限于文本,還有許多其他可能的輸出形式,包括matplotlib圖形和HTML表格(例如,在pandas數(shù)據(jù)分析包中使用的表格)。
我們看一個(gè)code cells的例子:
%%import numpy as npmy_arr = np.arange(1000000)my_list = list(range(1000000))
每個(gè)單元格是以 %% 來(lái)進(jìn)行分隔的。
Ipython本身還支持多種富文本的展示格式,包括HTML,JSON,PNG,JPEG,SVG,LaTeX等。
Ipython提供了一個(gè)display方法,我們可以使用display來(lái)展示要呈現(xiàn)的對(duì)象:
from IPython.display import display
display(obj) 將會(huì)尋找這個(gè)對(duì)象所有可能的展示類型,并從中挑選一個(gè)最適合的類型進(jìn)行展示,并將結(jié)果存儲(chǔ)在Notebook文檔里面。
如果你想展示特定類型的對(duì)象,那么可以這樣:
from IPython.display import ( display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg)
舉個(gè)展示圖片的例子:
from IPython.display import Imagei = Image(filename=&39;../images/ipython_logo.png&39;)idisplay(i)
上面的例子中i包含了一個(gè)Image對(duì)象,直接調(diào)用i即可展示,我們也可以顯示的調(diào)用display(i)。
其他的富文本類型可以參考Image,使用方法都是類似的。
markdown是一種簡(jiǎn)介的標(biāo)記語(yǔ)言,使用起來(lái)非常簡(jiǎn)單,使用范圍非常廣泛,所以notebook document也支持markdown的語(yǔ)法。
先看一個(gè)markdown cell的例子:
%% md```python$ pythonPython 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 linuxType &34;help&34;, &34;copyright&34;, &34;credits&34; or &34;license&34; for more information.>>> a = 5>>> print(a)5```
markdown中的語(yǔ)法在notebook中都是可以用的。
還支持標(biāo)準(zhǔn)的LaTeX 和 AMS-LaTeX語(yǔ)法。
原始單元格提供了一個(gè)可以直接寫(xiě)入輸出的位置。 notebook不會(huì)對(duì)原始單元格中的內(nèi)容進(jìn)行計(jì)算。
有時(shí)候我們希望以模塊的形式導(dǎo)入Jupyter Notebooks,但是可惜的是,Jupyter Notebooks并不是一個(gè)標(biāo)準(zhǔn)的python程序,不過(guò)Python提供了一些鉤子程序,讓我們能夠方便的進(jìn)行導(dǎo)入。
首先,我們需要導(dǎo)入一些基本的API :
import io, os, sys, typesfrom IPython import get_ipythonfrom nbformat import readfrom IPython.core.interactiveshell import InteractiveShell
接下來(lái)需要注冊(cè)NotebookFinder到sys.meta_path:
sys.meta_path.append(NotebookFinder())
這個(gè)NotebookFinder就是定義的鉤子。
我們看下NotebookFinder的定義:
class NotebookFinder(object): &34;&34;&34;Module finder that locates Jupyter Notebooks&34;&34;&34; 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&39;t hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key]
里面使用了兩個(gè)重要的方法,find_notebook用來(lái)找到notebook,和NotebookLoader,用來(lái)加載notebook。
看下find_notebook的定義:
def find_notebook(fullname, path=None): &34;&34;&34;find a notebook, given its fully qualified name and an optional path This turns &34;foo.bar&34; into &34;foo/bar.ipynb&34; and tries turning &34;Foo_Bar&34; into &34;Foo Bar&34; if Foo_Bar does not exist. &34;&34;&34; name = fullname.rsplit(&39;.&39;, 1)[-1] if not path: path = [&39;&39;] for d in path: nb_path = os.path.join(d, name + &34;.ipynb&34;) if os.path.isfile(nb_path): return nb_path let import Notebook_Name find &34;Notebook Name.ipynb&34; nb_path = nb_path.replace(&34;_&34;, &34; &34;) if os.path.isfile(nb_path): return nb_path
看下NotebookLoader的定義:
class NotebookLoader(object): &34;&34;&34;Module Loader for Jupyter Notebooks&34;&34;&34; def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): &34;&34;&34;import a notebook as a module&34;&34;&34; path = find_notebook(fullname, self.path) print (&34;importing Jupyter notebook from %s&34; % path) load the notebook object with io.open(path, &39;r&39;, encoding=&39;utf-8&39;) 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__[&39;get_ipython&39;] = get_ipython sys.modules[fullname] = mod extra work to ensure that magics that would affect the user_ns actually affect the notebook module&39;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 == &39;code&39;: 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我們自己編寫(xiě)的notebook了。
了解更多本文已收錄于 http://www.flydean.com/12-jupyter-notebook/
最通俗的解讀,最深刻的干貨,最簡(jiǎn)潔的教程,眾多你不知道的小技巧等你來(lái)發(fā)現(xiàn)!
歡迎關(guān)注我的公眾號(hào):「程序那些事」,懂技術(shù),更懂你!
何俊東
版權(quán)所有 未經(jīng)許可不得轉(zhuǎn)載
增值電信業(yè)務(wù)經(jīng)營(yíng)許可證備案號(hào):遼ICP備14006349號(hào)
網(wǎng)站介紹 商務(wù)合作 免責(zé)聲明 - html - txt - xml