在jupyter notebook中調(diào)用.ipynb文件方式
正常來說在jupyter notebook 中只能調(diào)用.py文件,要想要調(diào)用jupyter notebook自己的文件會報錯。
Jupyter Notebook官網(wǎng)介紹了一種簡單的方法:
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html
添加jupyter notebook解析文件
首先,創(chuàng)建一個python文件,例如Ipynb_importer.py,代碼如下:
import io, os,sys,types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell 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] 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 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 sys.meta_path.append(NotebookFinder())
調(diào)用jupyter notebook module
只要在我們的工作目錄下放置Ipynb_importer.py文件,就可以正常調(diào)用所有的jupyter notebook文件。 這種方法的本質(zhì)就是使用一個jupyter notenook解析器先對.ipynb文件進(jìn)行解析,把文件內(nèi)的各個模塊加載到內(nèi)存里供其他python文件調(diào)用。
新建一個文件foo.ipynb
def foo(): print("foo")
再新建一個ipynb文件,調(diào)用foo這個文件
import Ipynb_importer import foo foo.foo()
運(yùn)行結(jié)果如下:
importing Jupyter notebook from foo.ipynb
foo
補(bǔ)充知識:jupyter notebook_主函數(shù)文件如何調(diào)用類文件
使用jupyter notebook編寫python程序,rw_visual.jpynb是寫的主函數(shù),random_walk.jpynb是類(如圖)。在主函數(shù)中將類實(shí)例化后運(yùn)行會報錯,經(jīng)網(wǎng)絡(luò)查找解決了問題,缺少Ipynb_importer.py這樣一個鏈接文件。
解決方法:
1、在同一路徑下創(chuàng)建名為Ipynb_importer.py的文件:File-->download as-->Python(.py),該文件內(nèi)容如下:
#!/usr/bin/env python # coding: utf-8 # In[ ]: import io, os,sys,types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell 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] 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 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 sys.meta_path.append(NotebookFinder())
2、在主函數(shù)中import Ipynb_importer
import matplotlib.pyplot as plt import Ipynb_importer from random_walk import RandomWalk rw = RandomWalk() rw.fill_walk() plt.scatter(rw.x_values, rw.y_values, s=15) plt.show()
3、運(yùn)行主函數(shù),調(diào)用成功
ps:random_walk.jpynb文件內(nèi)容如下:
from random import choice class RandomWalk(): def __init__(self, num_points=5000): self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): while len(self.x_values) < self.num_points: x_direction = choice([1,-1]) x_distance = choice([0,1,2,3,4]) x_step = x_direction * x_distance y_direction = choice([1,-1]) y_distance = choice([0,1,2,3,4]) y_step = y_direction * y_distance if x_step == 0 and y_step == 0: continue next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y)
運(yùn)行結(jié)果:
以上這篇在jupyter notebook中調(diào)用.ipynb文件方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python selenium文件上傳下載功能代碼實(shí)例
這篇文章主要介紹了Python selenium文件上傳下載功能代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04python 3.6 tkinter+urllib+json實(shí)現(xiàn)火車車次信息查詢功能
這篇文章主要介紹了python 3.6 tkinter+urllib+json 火車車次信息查詢功能,本文以查詢火車車次至南京的信息為例,需要的朋友可以參考下2017-12-12Python?合并/拆分Excel的實(shí)現(xiàn)示例
有時對于多個工作表需要進(jìn)行合并或拆分,以便進(jìn)行瀏覽總結(jié),本文主要介紹了Python?合并/拆分Excel的實(shí)現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2023-09-09關(guān)于Python調(diào)用百度語音合成SDK實(shí)現(xiàn)文字轉(zhuǎn)音頻的方法
這篇文章主要介紹了關(guān)于Python調(diào)用百度語音合成SDK實(shí)現(xiàn)文字轉(zhuǎn)音頻的方法,AipSpeech是語音合成的Python?SDK客戶端,為使用語音合成的開發(fā)人員提供了一系列的交互方法,需要的朋友可以參考下2023-07-07