Skip to content

🐍Python Coroutine

async/await 簡單範例

以下是一個簡單的範例,展示了如何使用async/await來執行兩個簡單的IO操作,並在其完成後進行後續處理:

python
import asyncio

async def fetch_data(url):
    print(f"Fetching data from {url}")
    # 模擬等待IO操作
    await asyncio.sleep(2)
    print(f"Data fetched from {url}")

async def main():
    task1 = fetch_data("https://example.com")
    task2 = fetch_data("https://another-site.com")
    
    await asyncio.gather(task1, task2)

asyncio.run(main())

在這個例子中,fetch_data函數模擬了一個IO操作,使用await asyncio.sleep(2)來模擬等待。main函數創建了兩個fetch_data的異步任務,並通過asyncio.gather同時等待它們的完成。

混合 bottle 和使用者的 Event Loop

python
import asyncio
from bottle import Bottle, run

app = Bottle()

async def custom_coroutine():
    print("Custom coroutine start")
    await asyncio.sleep(2)
    print("Custom coroutine end")

async def main():
    print("Bottle main start")
    await asyncio.sleep(1)
    print("Bottle main end")

@app.route('/')
def index():
    asyncio.ensure_future(custom_coroutine())  # 添加自己的協程到事件循環
    return "Hello, World!"

def start_bottle():
    run(app, host='localhost', port=8080)

async def run_all_coroutines():
    await asyncio.gather(main(), custom_coroutine())

if __name__ == '__main__':
    asyncio.run(run_all_coroutines())
    start_bottle()

Changelog

Just observe 👀