Difference between revisions of "Asyncio python"

From Teknologisk videncenter
Jump to: navigation, search
m (Links)
m
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
For a primer see [[Yield python]]
 
For a primer see [[Yield python]]
  
 +
=asyncio.create example=
 
await vs. asyncio.create()
 
await vs. asyncio.create()
  
Line 20: Line 21:
  
 
if __name__ == "__main__":
 
if __name__ == "__main__":
 +
    asyncio.run(main())
 +
</source>
 +
=asyncio.gather example=
 +
<source lang=python>
 +
import asyncio
 +
import aioping
 +
import time
 +
import datetime
 +
hosts = ['127.0.0.1', 'www.bmw.de', '8.8.8.8', "www.mercantec.dk","www.tdc.dk","92.38.178.249","www.audi.de","www.renault.fr"]
 +
 +
async def do_ping(host, timeout):
 +
    print(f" - Pinging {host}")
 +
    try:
 +
        return await aioping.ping(host, timeout) * 1000, host
 +
 +
    except TimeoutError:
 +
        return None, host
 +
 +
async def main():
 +
    t1 = time.time() # Timestamp start pings
 +
 +
    jobs = [do_ping(host, timeout=2) for host in hosts]
 +
 +
    print("Starting jobs:")
 +
    tasks = await asyncio.gather(*jobs)
 +
    print("Results are in:")
 +
 +
    for task in tasks:
 +
        if task[0]: # Or: if time is not None:
 +
            print(f" - It took {task[0]} mS to ping {task[1]}")
 +
        else:
 +
            print(f"{task[1]} is not responding")
 +
 +
    t2 = time.time() # Timestamp end pings
 +
 +
    print("========================================")
 +
    print(f"It took {t2-t1} seconds")
 +
    print("========================================")
 +
 +
if __name__ == '__main__':
 
     asyncio.run(main())
 
     asyncio.run(main())
 
</source>
 
</source>
 
=Links=
 
=Links=
 +
*[https://docs.python.org/3/library/asyncio-eventloop.html Event Loop]
 
*[https://realpython.com/async-io-python/ Async IO in Python]
 
*[https://realpython.com/async-io-python/ Async IO in Python]
 
*[https://realpython.com/python-gil/ The Python GIL - Global Interpreter Lock]
 
*[https://realpython.com/python-gil/ The Python GIL - Global Interpreter Lock]
 
*[https://realpython.com/python-concurrency/ Speed Up Your Python Program With Concurrency]
 
*[https://realpython.com/python-concurrency/ Speed Up Your Python Program With Concurrency]
 +
*[https://realpython.com/async-io-python/ Async IO in Python: A Complete Walkthrough]
  
 
[[Category:Python]]
 
[[Category:Python]]

Latest revision as of 09:29, 2 March 2025

For a primer see Yield python

asyncio.create example

await vs. asyncio.create()

import asyncio
import time

async def fetch_data(url):
    # Simulate a long-running network request
    await asyncio.sleep(2)  # Wait for 2 seconds
    print(f"Data fetched from {url}")

async def main():
    task1 = asyncio.create_task(fetch_data("https://example.com"))
    task2 = asyncio.create_task(fetch_data("https://another.example.com"))

    await task1
    await task2

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

asyncio.gather example

import asyncio
import aioping
import time
import datetime
hosts = ['127.0.0.1', 'www.bmw.de', '8.8.8.8', "www.mercantec.dk","www.tdc.dk","92.38.178.249","www.audi.de","www.renault.fr"]

async def do_ping(host, timeout):
    print(f" - Pinging {host}")
    try:
        return await aioping.ping(host, timeout) * 1000, host

    except TimeoutError:
        return None, host

async def main():
    t1 = time.time() # Timestamp start pings

    jobs = [do_ping(host, timeout=2) for host in hosts]

    print("Starting jobs:")
    tasks = await asyncio.gather(*jobs)
    print("Results are in:")

    for task in tasks:
        if task[0]: # Or: if time is not None:
            print(f" - It took {task[0]} mS to ping {task[1]}")
        else:
            print(f"{task[1]} is not responding")

    t2 = time.time() # Timestamp end pings

    print("========================================")
    print(f"It took {t2-t1} seconds")
    print("========================================")

if __name__ == '__main__':
    asyncio.run(main())

Links