Python await 關鍵字



Python 的 await 關鍵字用於暫停一個 協程。協程是一個能夠在遇到可能需要一段時間才能完成的操作時暫停其執行的函式。

當長時間執行的操作完成後,我們可以恢復暫停的協程並在該協程中執行剩餘的程式碼。在協程等待長時間執行的操作時,我們可以執行其他程式碼。透過這樣做,我們可以非同步執行程式以提高其效能。

語法

以下是 Python await 關鍵字的語法:

await

示例

以下是 Python await 關鍵字的基本示例:

import asyncio
# Define the asynchronous function
async def cube(number):
    return number * number * number
# Main function to run the coroutine
async def main():
    # Await the result of the cube function
    result = await cube(10)
    print(result)
# Run the main function
asyncio.run(main())

輸出

以下是以上程式碼的輸出:

1000

使用 'await' 與 sleep()

sleep() 用於將執行暫停指定時間段。它接受一個整數值。

示例

在這裡,我們使用 sleep()await 關鍵字將函式暫停了一秒鐘:

import asyncio
async def say_hello():
    print("Hello!")
    await asyncio.sleep(1)  # Pauses the execution for 1 second
    print("World!")
async def main():
    print("Start")
    await say_hello()  # Waits for the say_hello coroutine to complete
    print("End")
# Run the main coroutine
asyncio.run(main())

輸出

以下是以上程式碼的輸出:

Start
Hello!
World!
End
python_keywords.htm
廣告