【发布时间】:2020-08-18 19:53:52
【问题描述】:
我正在尝试永远运行 2 个async 函数。有人能帮我吗?下面提供了我的代码和错误消息。
代码:
import websockets
import asyncio
import json
import time
async def time(loop):
while True:
millis = await int(round(time.time() * 1000))
print(millis)
await asyncio.sleep(0.001)
async def stream(loop):
async with websockets.connect('wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD')
as websocket:
while True:
try:
data = await websocket.recv()
data = json.loads(data)
print(data['data'][-1]['price'])
except KeyError:
pass
except TypeError:
pass
loop = asyncio.get_event_loop()
async def main():
await asyncio.gather(loop.run_until_complete(stream(loop)),
loop.run_until_complete(time(loop)))
if __name__ == "__main__":
asyncio.run(main())
错误:
Exception has occurred: RuntimeError
Cannot run the event loop while another loop is running
【问题讨论】:
-
你是如此接近 - 只需删除
loop.run_until_complete,一切都会正常。 (另外,在int之前删除await,正如答案中所指出的那样。)
标签: python asynchronous python-asyncio