簡體   English   中英

Asyncio 收集一個 while 循環

[英]Asyncio Gathering a while loop

這是我的代碼的簡化版本,但問題是相同的:

import asyncio

example = ["1", "2", "3", "4", "5"]

def test_1(numbers):
    while True:
        print(numbers)

tasks = []
async def test_2():
    for numbers in example:
        try:
            tasks.append(test_1(numbers))
        except:
            pass
    try:
        await asyncio.gather(*tasks)
    except:
        pass

asyncio.run(test_2())

我想要做的是在 while 循環中同時打印所有項目,但是當我運行代碼時,它只打印第一個項目,因為它是循環的,有沒有辦法解決它?

好的,感謝@deceze,我修復了它,我以這種方式使用線程:

for numbers in example:
    t = threading.Thread(target=test_1, args=(numbers,))
    threads.append(t)
    t.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM