Async/Await Experts advice needed

The code below works very well.
Just wondering if the for/in loop should be wrapped in a coroutine.

import asyncio
from scrapli.driver.core import AsyncIOSXEDriver

with open("addresses.txt") as f1:
    f1 = f1.read().splitlines()

device_list = []

# should I wrap it in a coroutine ?
for ip in f1:
        device = {
            "host": ip,
            "auth_username": "user1",
            "auth_password": "secret1",
            "auth_strict_key": False,
            "transport": "asyncssh",
        }
        device_list.append(device)

async def task1(x):
    async with AsyncIOSXEDriver(**x) as conn:
        output = await conn.send_commands([
            "show run | inc hostname", "\n",
            "sh vlan brief", "\n"
            ])
        return output

async def main():
    coroutines = [task1(y) for y in device_list]
    results = await asyncio.gather(*coroutines)
    for r in results:
        print(r.result)

if __name__ == "__main__":
    asyncio.run(main())
    #asyncio.get_event_loop().run_until_complete(main())

Coroutines allow you to delay operations until something gets you a result. In your example, send_commands presumably will let you know when it’s finished sending those commands; but, importantly, you can send commands to OTHER connections at the same time, so it makes good sense to have these as tasks with await points in them.

But the loop in this code (I presume you’re talking about for ip in f1 - the same is true of for r in results too) doesn’t do anything that works that way. All it’s doing os building up a list of dictionaries, which can be done synchronously (the opposite of asynchronously which is where async functions come in). So there’s no need to wrap it in a coroutine here.

Generally, you only need to wrap something in a coroutine if it has an await, or some equivalent contruct (async with and async for have inbuilt await statements). Otherwise, it’s usually fine as it is.

1 Like

Alright. The coroutine is usually used with specific functions and it depends on the code’s purpose.
Then, the code is fine so.
Thank you !

BTW, do you know more about the argument RESULT in Print ? It seems to be an argument, not just an defined object.
I want to tidy up the output, but I’m stuck. print(r.result + ‘\n’) doesn’t work.
There is probably a particular way to deal with RESULT.

The output looks now as below. in the same line per device.

device1
command1command2command3

device2
command1command2command3

I want to separate the outputs like this:

device 1
command1
command2
command3

device 2
command1
command2
command3