Mik*_*ike 6 python ipython jupyter-notebook
IPython 中是否有一种方法可以将import笔记本单元的内容视为一个单独的模块?或者让单元格的内容拥有自己的命名空间。
@Mike,正如评论中提到的,您可以按照以下链接中详细记录的步骤将 Jupyter Notebook 导入为模块:
在链接中,他们将提到 Python 中为用户提供钩子(现在已被importlib和import system取代)所做的工作,以提供更好的导入机制自定义。
因此,他们提出的配方如下:
- 将笔记本文档加载到内存中
- 创建一个空模块
- 执行模块命名空间中的每个单元
,并且他们为Notebook Loader提供了自己的实现(如果代码都是纯 python,则不需要):
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
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
最后一步是新模块的注册:
sys.meta_path.append(NotebookFinder())
Run Code Online (Sandbox Code Playgroud)
然而,所有这些都是来自此答案中给出的第一个链接的直接引用。该文档构建良好,并提供了其他内容的答案,例如显示笔记本或处理包。
| 归档时间: |
|
| 查看次数: |
2699 次 |
| 最近记录: |