python – 加载Jupyter Server Extension时找不到模块

我想在本地目录中加载Jupyter Notebook Server Extension

server_ext/
|__  __init__.py
|__  extension.py

extension.py

from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler

class HelloWorldHandler(IPythonHandler):
    def get(self):
        self.finish('Hello, world!')

def load_jupyter_server_extension(nbapp):
    """
    nbapp is istance of Jupyter.notebook.notebookapp.NotebookApp
    nbapp.web_app is isntance of tornado.web.Application - can register new tornado.web.RequestHandlers
    to extend API backend.
    """
    nbapp.log.info('My Extension Loaded')
    web_app = nbapp.web_app
    host_pattern = '.*$'
    route_pattern = url_path_join(web_app.settings['base_url'], '/hello')
    web_app.add_handlers(host_pattern, [(route_pattern, HelloWorldHandler)])

我从包含server_ext的目录运行以下命令:

jupyter notebook --NotebookApp.server_extensions="['server_ext.extension']"

但我收到错误“没有模块命名扩展名”.为了让Jupyter / python会话识别模块的路径,我有什么必须做的吗?

最佳答案
弄清楚了-

事实证明,Jupyter Notebook对importlib.import_module的调用设置了package = None,这意味着相对路径不起作用.

作为解决方法,可以修改〜/ .jupyter / jupyter_notebook_config.py脚本以将本地目录附加到PYTHONPATH,以便可以找到该模块.

import sys
sys.path.append("C:\\Users\\eric\\server_ext")

c.NotebookApp.server_extensions = [
    'extension'
]

转载注明原文:python – 加载Jupyter Server Extension时找不到模块 - 代码日志