IPython 中是否有一种方法可以导入
笔记本单元格的内容,就好像它是一个单独的模块一样?或者让单元格的内容拥有自己的命名空间。
最佳答案
@Mike,如评论中所述,您可以按照以下链接中记录良好的步骤将 Jupyter Notebook 作为模块导入:
Importing Jupyter Notebooks as Modules
在链接中,他们将提到用 Python 完成的工作,为用户提供 hooks (现已被 importlib 和 import system 取代)以提供更好的导入机制定制。
因此,他们建议的配方如下:
- load the notebook document into memory
- create an empty Module
- execute every cell in the Module namespace
,他们为 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
这也是 Notebook Finder 的实现:
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]
最后一步是 registration新模块:
sys.meta_path.append(NotebookFinder())
但是,所有这些都是直接引用此答案中给出的第一个链接。该文档构建良好,并提供了其他内容的答案,例如 displaying notebooks或处理 packages .
关于python - IPython/Jupyter notebook cell 可以像模块一样导入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337792/