I have the following excerpt which works fine in every regard except that it requires that I know how many WebSockets I plan to open in advance.
If instead I started with a list of hosts and had to create N WebSocket connections, how could I accomplish what this code does for 3 Websockets (via 'async with') for N in a loop?
The awaiting I already have in a loop, it's the "async with" that I cannot figure out how to "loopify".
async with websockets.connect('ws://192.168.0.174:81') as websocket1:
async with websockets.connect('ws://192.168.0.194:81') as websocket2:
async with websockets.connect('ws://192.168.0.179:81') as websocket3:
datatosend = GetBallData()
for socket in [websocket1, websocket2, websocket3]:
await socket.send(datatosend)
Starting from Python3.7 there is AsyncExitStack available in contextlib
module, this is how it can be used for your issue:
hosts = ['ws://192.168.0.174:81', 'ws://192.168.0.194:81', 'ws://192.168.0.179:81']
async with contextlib.AsyncExitStack() as stack:
sockets = [
await stack.enter_async_context(websockets.connect(host))
for host in hosts
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With