Difference between revisions of "Asyncio python"
From Teknologisk videncenter
m |
m |
||
Line 1: | Line 1: | ||
For a primer see [[Yield python]] | For a primer see [[Yield python]] | ||
+ | await vs. asyncio.create() | ||
+ | |||
+ | <source lang=python> | ||
+ | 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()) | ||
+ | </source> | ||
=Links= | =Links= | ||
*[https://realpython.com/async-io-python/ Async IO in Python] | *[https://realpython.com/async-io-python/ Async IO in Python] |
Latest revision as of 09:03, 5 October 2024
For a primer see Yield python
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())