Asyncio RuntimeError: readuntil() called while another coroutine is already waiting for incoming data

Viewed 1090

Using python3.6.8:

I'm attempting to script the initial configuration of network devices on boot. My script opens telnet connection on "ip_addr:port". Once connected, script stimulates the network device it's connecting to with "\n\n" (simulating two 'Enter' input from an admin).

connection = asyncio.open_connection(
                 ip_addr,
                 port,
             )
try:
    reader, writer = await asyncio.wait_for(connection, 5)
    print(f"successfully connected to {ip_addr}:{port}")
    writer.write(b'\n\n\n')

Some devices are already configured and I except " login: " to show up in the read buffer upon entering '\n'. However if the device is not configured yet, " login: " will not show up in the buffer. Therefore I thought I could use wait_for and timeout option to have this cancelled and move on with another reader.readuntil(...) expecting another output.

try:
    await asyncio.wait_for(reader.readuntil(b' login: '), 3)
    print(f"{ip_addr}:{port} alredy booted")
    break
except (asyncio.TimeoutError, OSError):
    print('Nope, moving forward')
    await reader.readuntil(b'normal setup ?(yes/no)[n]: ')

However this raises a RuntimeError. Reading the documentation I excepted the task to be cancelled if the timeout is reached, so why can't it have another coroutine readuntil() ?

0 Answers
Related