在jupyter notebook中调用.ipynb文件方式


Posted in Python onApril 14, 2020

正常来说在jupyter notebook 中只能调用.py文件,要想要调用jupyter notebook自己的文件会报错。

Jupyter Notebook官网介绍了一种简单的方法:

http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html

添加jupyter notebook解析文件

首先,创建一个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())

调用jupyter notebook module

只要在我们的工作目录下放置Ipynb_importer.py文件,就可以正常调用所有的jupyter notebook文件。 这种方法的本质就是使用一个jupyter notenook解析器先对.ipynb文件进行解析,把文件内的各个模块加载到内存里供其他python文件调用。

新建一个文件foo.ipynb

def foo():
 print("foo")

再新建一个ipynb文件,调用foo这个文件

import Ipynb_importer
import foo
foo.foo()

运行结果如下:

importing Jupyter notebook from foo.ipynb
foo

补充知识:jupyter notebook_主函数文件如何调用类文件

使用jupyter notebook编写python程序,rw_visual.jpynb是写的主函数,random_walk.jpynb是类(如图)。在主函数中将类实例化后运行会报错,经网络查找解决了问题,缺少Ipynb_importer.py这样一个链接文件。

在jupyter notebook中调用.ipynb文件方式

解决方法:

1、在同一路径下创建名为Ipynb_importer.py的文件:File-->download as-->Python(.py),该文件内容如下:

#!/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、在主函数中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、运行主函数,调用成功

ps:random_walk.jpynb文件内容如下:

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)

运行结果:

在jupyter notebook中调用.ipynb文件方式

以上这篇在jupyter notebook中调用.ipynb文件方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python处理json数据中的中文
Mar 06 Python
Python中type的构造函数参数含义说明
Jun 21 Python
python MysqlDb模块安装及其使用详解
Feb 23 Python
Python OpenCV对本地视频文件进行分帧保存的实例
Jan 08 Python
python pip安装包出现:Failed building wheel for xxx错误的解决
Dec 25 Python
解决pyinstaller打包运行程序时出现缺少plotly库问题
Jun 02 Python
Python如何使用vars返回对象的属性列表
Oct 17 Python
Docker如何部署Python项目的实现详解
Oct 26 Python
python实现录音功能(可随时停止录音)
Oct 26 Python
python实现监听键盘
Apr 26 Python
python中的getter与setter你了解吗
Mar 24 Python
python中Pyqt5使用Qlabel标签播放视频
Apr 22 Python
使用jupyter notebook将文件保存为Markdown,HTML等文件格式
Apr 14 #Python
Python使用pyyaml模块处理yaml数据
Apr 14 #Python
Jupyter Notebook打开任意文件夹操作
Apr 14 #Python
Python requests模块cookie实例解析
Apr 14 #Python
Python requests模块session代码实例
Apr 14 #Python
使用Jupyter notebooks上传文件夹或大量数据到服务器
Apr 14 #Python
服务器端jupyter notebook映射到本地浏览器的操作
Apr 14 #Python
You might like
关于php正则匹配汉字的方法介绍
2013/04/25 PHP
在PHP模板引擎smarty生成随机数的方法和math函数详解
2014/04/24 PHP
PHP文件上传类实例详解
2016/04/08 PHP
JAVASCRIPT 对象的创建与使用
2021/03/09 Javascript
前端开发的开始---基于面向对象的Ajax类
2010/09/17 Javascript
基于jquery的无刷新分页技术
2011/06/11 Javascript
用JS做的简单的可折叠的两级树形菜单
2013/09/21 Javascript
使用 Node.js 做 Function Test实现方法
2013/10/25 Javascript
jquery trigger伪造a标签的click事件取代window.open方法
2014/06/23 Javascript
c#+jquery实现获取radio和checkbox的值
2020/09/12 Javascript
让JavaScript中setTimeout支持链式操作的方法
2015/06/19 Javascript
Javascript控制div属性动态变化实例分析
2015/10/08 Javascript
JS中call/apply、arguments、undefined/null方法详解
2016/02/15 Javascript
jQuery on()绑定动态元素出现的问题小结
2016/02/19 Javascript
jQuery 监控键盘一段时间没输入
2016/04/22 Javascript
深入理解jQuery之防止冒泡事件
2016/05/24 Javascript
微信小程序五星评分效果实现代码
2017/04/06 Javascript
[56:35]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第一局
2016/03/06 DOTA
用Python写的图片蜘蛛人代码
2012/08/27 Python
python获得图片base64编码示例
2014/01/16 Python
Python中map,reduce,filter和sorted函数的使用方法
2015/08/17 Python
一篇文章入门Python生态系统(Python新手入门指导)
2015/12/11 Python
python清除字符串中间空格的实例讲解
2018/05/11 Python
django认证系统 Authentication使用详解
2019/07/22 Python
python实现猜拳小游戏
2020/04/05 Python
Tensorflow实现将标签变为one-hot形式
2020/05/22 Python
python实现AHP算法的方法实例(层次分析法)
2020/09/09 Python
css3实现画半圆弧线的示例代码
2017/11/06 HTML / CSS
大专毕业生自我鉴定
2013/11/21 职场文书
司机辞职报告范文
2014/01/20 职场文书
大学生党校培训心得体会
2014/09/11 职场文书
安全生产先进个人事迹材料
2014/12/30 职场文书
CSS预处理框架——Stylus
2021/04/21 HTML / CSS
Python快速优雅的批量修改Word文档样式
2021/05/20 Python
Mysql 设置boolean类型的操作
2021/06/04 MySQL
Go timer如何调度
2021/06/09 Golang