我正在使用asyncio和websockets在Jupyter Notebooks上工作,除了重新启动内核外,我找不到其他方法来关闭事件循环。
我已经尝试过loop.stop()和loop.close(),但是它抛出了这个错误:
RuntimeError: Cannot close a running event loop
如果每次运行jupyter单元后都没有重新启动内核,则仍会在先前运行的输出中打印出订阅,(我尝试注释await socket.send(msg)
以查看是否仍然得到如果我在进行另一次运行时不重新启动内核,则会打印一些订阅,并且可以)。
我对asyncio和websockets还是很陌生,所以我真的不明白这里发生了什么:是因为asyncio,websockets,还是jupyter?在websockets文档中,他们说带有with
语句的上下文管理器应该执行自动关闭或类似的操作,但是我想我没有以正确的方式使用它。我通过在jupyter界面上按“中断”来停止运行,我不知道这是否也与我在此处遇到的错误有关。
import json
import asyncio
import nest_asyncio
nest_asyncio.apply()
import websockets
async def message1():
async with websockets.connect("wss://url.example.com") as socket:
msg = #some json message
await socket.send(msg)
while True:
await asyncio.sleep(0.1)
answer = await socket.recv()
answer = json.loads(answer)
print(answer)
async def message2():
async with websockets.connect("wss://url.example.com") as socket:
msg = #some other json message
await socket.send(msg)
while True:
await asyncio.sleep(0.1)
answer = await socket.recv()
answer = json.loads(answer)
print(answer)
try:
loop = asyncio.get_event_loop()
cors = asyncio.wait([message1(), message2()])
loop.run_until_complete(cors)
finally:
loop.stop()
loop.close()