在jupyter notebook中調(diào)用.ipynb文件方式
正常來(lái)說(shuō)在jupyter notebook 中只能調(diào)用.py文件,要想要調(diào)用jupyter notebook自己的文件會(huì)報(bào)錯(cuò)。
Jupyter Notebook官網(wǎng)介紹了一種簡(jiǎn)單的方法:
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html
添加jupyter notebook解析文件
首先,創(chuàng)建一個(gè)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ì)就是使用一個(gè)jupyter notenook解析器先對(duì).ipynb文件進(jìn)行解析,把文件內(nèi)的各個(gè)模塊加載到內(nèi)存里供其他python文件調(diào)用。
新建一個(gè)文件foo.ipynb
def foo():
print("foo")
再新建一個(gè)ipynb文件,調(diào)用foo這個(gè)文件
import Ipynb_importer import foo foo.foo()
運(yùn)行結(jié)果如下:
importing Jupyter notebook from foo.ipynb
foo
補(bǔ)充知識(shí):jupyter notebook_主函數(shù)文件如何調(diào)用類文件
使用jupyter notebook編寫(xiě)python程序,rw_visual.jpynb是寫(xiě)的主函數(shù),random_walk.jpynb是類(如圖)。在主函數(shù)中將類實(shí)例化后運(yùn)行會(huì)報(bào)錯(cuò),經(jīng)網(wǎng)絡(luò)查找解決了問(wèn)題,缺少Ipynb_importer.py這樣一個(gè)鏈接文件。

解決方法:
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文件方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python計(jì)算元素在列表中出現(xiàn)的次數(shù)實(shí)例
本文介紹如何在Python中定義一個(gè)列表,并使用count()方法計(jì)算某個(gè)元素在列表中出現(xiàn)的次數(shù),示例中展示了具體的操作步驟和輸出結(jié)果2024-11-11
python實(shí)現(xiàn)單鏈表中刪除倒數(shù)第K個(gè)節(jié)點(diǎn)的方法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)單鏈表中刪除倒數(shù)第K個(gè)節(jié)點(diǎn)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
Python批量處理工作簿和工作表的實(shí)現(xiàn)示例
本文主要介紹了使用Python批量處理工作簿和工作表,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Python?BeautifulSoup4實(shí)現(xiàn)數(shù)據(jù)解析與提取
Beautiful?Soup是一個(gè)Python的庫(kù),用于解析HTML和XML文檔,提供了方便的數(shù)據(jù)提取和操作功能,下面小編就來(lái)和大家詳細(xì)聊聊如何利用BeautifulSoup4實(shí)現(xiàn)數(shù)據(jù)解析與提取吧2023-10-10
關(guān)于VSCode?配置使用?PyLint?語(yǔ)法檢查器的問(wèn)題
這篇文章主要介紹了VSCode?配置使用?PyLint?語(yǔ)法檢查器,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
python爬蟲(chóng)構(gòu)建代理ip池抓取數(shù)據(jù)庫(kù)的示例代碼
這篇文章主要介紹了python爬蟲(chóng)構(gòu)建代理ip池抓取數(shù)據(jù)庫(kù)的示例代碼,幫助大家更好的使用爬蟲(chóng),感興趣的朋友可以了解下2020-09-09
Python如何解決secure_filename對(duì)中文不支持問(wèn)題
最近使用到了secure_filename,然后悲劇的發(fā)現(xiàn)中文居然不展示出來(lái),本文就詳細(xì)的介紹一下解決方法,感興趣的可以了解一下2021-07-07

