October 25, 2024
Chicago 12, Melborne City, USA
python

Why my async function seems not to run asynchronously?


I want to (quickly) scan my LAN to find a host listening to a certain TCP port, e.g. 2442 (JS8Call network API, if anyone’s interested).

I copied program structure from a tutorial explaining asynchronous execution in python with the help of asyncio package. The program kind of works, but the individual tasks do not run in parallel, instead they run in sequence although the task creation and result collection seems to be OK. When it runs, I can see the print messages from async function ping appearing sequentially, the next one always appearing exactly after the previous one timed out.

What is wrong with my ping function? It does not seem to create a coroutine object, I guess.

#!/usr/bin/python

import socket
import asyncio

socket.setdefaulttimeout(0.5)

async def ping(host, port):
  r = f'{host}:{port} OK'
  try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
      s.connect( (host, port) )
      print( r )
      s.close()
      return r
  except Exception as X:
    print(f'{host} FAILED')
    return X

async def main():
  tasks = []
  async with asyncio.TaskGroup() as tg:
    # start all tasks
    for i in range(5,240):
      host = f'192.168.33.{i}'
      t = tg.create_task( ping(host, 22) )
      tasks.append(t)
  results = [ task.result() for task in tasks ]
  for p in results:
    if p != None:
      print(p)

asyncio.run( main() )



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video