【问题标题】:Asyncio Gathering a while loopAsyncio 收集一个 while 循环
【发布时间】:2021-07-20 12:56:23
【问题描述】:

这是我的代码的简化版本,但问题是一样的:

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循环中同时打印所有项目,但是当我运行代码时它只打印第一个项目,因为它是循环的,有没有办法修复它?

【问题讨论】:

  • 该函数需要await 某处以暂停并允许其他代码运行,或者您需要实际上使用线程并行运行它们。
  • 如何线程化使用不同项目的相同函数?我应该使用不同的参数吗?

标签: python loops while-loop python-requests python-asyncio


【解决方案1】:

好的,感谢@deceze,我修复了它,我以这种方式使用线程:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 2011-08-09
    • 2020-11-02
    • 2015-05-11
    相关资源
    最近更新 更多