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 =

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",

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:

if __name__ == "__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.



I want to separate the outputs like this:

device 1

device 2