1

我正在尝试在 Jupyter 上运行 justpy 网络应用程序,例如这个:

import justpy as jp

def hello_world():
    wp = jp.WebPage()
    d = jp.Div(text='Hello world!')
    wp.add(d)
    return wp

jp.justpy(hello_world)

但无论我在 Jupyter Notebook 或 Jupyter Lab 上运行它,它总是会产生错误:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-a5b426517caf> in <module>
      7     return wp
      8 
----> 9 jp.justpy(hello_world)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/justpy/justpy.py in justpy(func, start_server, websockets, host, port, startup, **kwargs)
    381                         ssl_keyfile=SSL_KEYFILE, ssl_certfile=SSL_CERTFILE, ssl_version=SSL_VERSION)
    382         else:
--> 383             uvicorn.run(app, host=host, port=port, log_level=UVICORN_LOGGING_LEVEL)
    384 
    385     return func_to_run

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/uvicorn/main.py in run(app, **kwargs)
    389         supervisor.run()
    390     else:
--> 391         server.run()
    392 
    393 

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/uvicorn/main.py in run(self, sockets)
    417         self.config.setup_event_loop()
    418         loop = asyncio.get_event_loop()
--> 419         loop.run_until_complete(self.serve(sockets=sockets))
    420 
    421     async def serve(self, sockets=None):

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py in run_until_complete(self, future)
    590         """
    591         self._check_closed()
--> 592         self._check_running()
    593 
    594         new_task = not futures.isfuture(future)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py in _check_running(self)
    550     def _check_running(self):
    551         if self.is_running():
--> 552             raise RuntimeError('This event loop is already running')
    553         if events._get_running_loop() is not None:
    554             raise RuntimeError(

RuntimeError: This event loop is already running

有没有人有在 Jupyter 上运行 justpy 应用程序的解决方案?

4

2 回答 2

1

安装嵌套异步

pip install nest-asyncio

之后添加以下行

import nest_asyncio
nest_asyncio.apply()
__import__('IPython').embed()
于 2021-04-06T17:02:01.873 回答
1

在笔记本的开头添加这个

import nest_asyncio
nest_asyncio.apply()

这是因为 ipython 内核本身在事件循环上运行,
并引用nest_asyncio文档:

按照设计,asyncio 不允许嵌套其事件​​循环。这提出了一个实际问题:在事件循环已经运行的环境中,不可能运行任务并等待结果。尝试这样做会给出错误“RuntimeError: This event loop is already running”。

于 2021-04-06T16:13:28.147 回答