如何让 SocketIO/aiohttp 每 X 秒打印到屏幕
How to make SocketIO/aiohttp print to screen every X seconds
使用 aiohttp 创建的 SocketIO 服务器在从其 socketio 客户端接收到 addAnimal
消息时将新字符串附加到全局字典 zoo
。
是否也可以每 5 秒打印一次字典 zoo
?我下面的当前代码似乎没有每 5 秒打印一次 zoo
。
import time
from aiohttp import web
import socketio
zoo = []
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
@sio.on('addAnimal')
async def onAddAnimal(sid, animal):
zoo.append(animal)
print('Zoo: ', zoo)
if __name__ == '__main__':
web.run_app(app)
while True:
print('Zoo:', zoo)
time.delay(5)
试试这个。
from aiohttp import web
import socketio
zoo = []
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
async def print_zoo(interval: int):
while True:
print(zoo)
await asyncio.sleep(interval)
@sio.on('addAnimal')
async def onAddAnimal(sid, animal):
zoo.append(animal)
print('Zoo: ', zoo)
if __name__ == '__main__':
asyncio.ensure_future(print_zoo(5))
web.run_app(app)
使用 aiohttp 创建的 SocketIO 服务器在从其 socketio 客户端接收到 addAnimal
消息时将新字符串附加到全局字典 zoo
。
是否也可以每 5 秒打印一次字典 zoo
?我下面的当前代码似乎没有每 5 秒打印一次 zoo
。
import time
from aiohttp import web
import socketio
zoo = []
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
@sio.on('addAnimal')
async def onAddAnimal(sid, animal):
zoo.append(animal)
print('Zoo: ', zoo)
if __name__ == '__main__':
web.run_app(app)
while True:
print('Zoo:', zoo)
time.delay(5)
试试这个。
from aiohttp import web
import socketio
zoo = []
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
async def print_zoo(interval: int):
while True:
print(zoo)
await asyncio.sleep(interval)
@sio.on('addAnimal')
async def onAddAnimal(sid, animal):
zoo.append(animal)
print('Zoo: ', zoo)
if __name__ == '__main__':
asyncio.ensure_future(print_zoo(5))
web.run_app(app)