我正在創建一個執行以下操作的 python 代碼:
1 - 創建一個名為“nums”的異步函式,然后每 2 秒列印 0 到 10 的亂數。2 - 執行每 5 秒列印一次“hello world”的函式。3 - 如果函式“nums”列印 1 或 3,則中斷回圈并結束程式。
問題是,它并沒有跳出回圈。我應該怎么做?謝謝你。
import asyncio
import random
async def nums():
while True:
x = print(random.randint(0, 10))
await asyncio.sleep(2)
if x == 1 or x == 3:
break
async def world():
while True:
print("hello world")
await asyncio.sleep(5)
async def main():
while True:
await asyncio.wait([nums(), world()])
if __name__ == '__main__':
asyncio.run(main())
uj5u.com熱心網友回復:
您可以return_when=asyncio.FIRST_COMPLETED在中使用引數asyncio.wait:
import asyncio
import random
async def nums():
while True:
x = random.randint(0, 10)
print(x)
if x in {1, 3}
break
await asyncio.sleep(2)
async def world():
while True:
print("hello world")
await asyncio.sleep(5)
async def main():
task1 = asyncio.create_task(nums())
task2 = asyncio.create_task(world())
await asyncio.wait({task1, task2}, return_when=asyncio.FIRST_COMPLETED)
if __name__ == "__main__":
asyncio.run(main())
列印(例如):
5
hello world
6
6
hello world
1
<program ends here>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517864.html
標籤:Python异步蟒蛇异步
