问题描述
我正在尝试永远运行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
解决方法
好,您的代码段错误很少:
- 您不能将第一个函数命名为
time
,因为它会与time
内置函数产生冲突 - 为什么不使用
loop
作为参数呢?这没用。 - 如果无法等待某个功能,则无法
await
,即int
是一个内置的同步方法。
进行正确的更正将是这样的:
import websockets
import asyncio
import json
import time
async def another_name():
while True:
millis = int(round(time.time() * 1000))
print(millis)
await asyncio.sleep(0.001)
async def stream():
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
await asyncio.sleep(0.001) #Added
if __name__ == "__main__":
loop = asyncio.get_event_loop()
coros = []
coros.append(another_name())
coros.append(stream())
loop.run_until_complete(asyncio.gather(*coros))
await asyncio.sleep(0.001)
函数中的行stream()
是强制性的,否则它将永远不会让another_name()
函数运行。