簡體   English   中英

在 Jupyter 上運行 justpy web 應用程序返回 RuntimeError

[英]Running a justpy web app on Jupyter returns RuntimeError

我正在嘗試在 Jupyter 上運行 justpy web 應用程序,例如這個:

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 應用程序的解決方案?

在筆記本的開頭添加這個

import nest_asyncio
nest_asyncio.apply()

這是因為 ipython kernel 本身在事件循環上運行,
並引用nest_asyncio文檔:

按照設計,asyncio 不允許嵌套其事件循環。 這提出了一個實際問題:在事件循環已經運行的環境中,不可能運行任務並等待結果。 嘗試這樣做會給出錯誤“RuntimeError: This event loop is already running”。

安裝嵌套異步

pip install nest-asyncio

之后添加以下行

import nest_asyncio
nest_asyncio.apply()
__import__('IPython').embed()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM