【问题标题】:How to combine a dynamic amount (150-200) of async functions for calculation purposes如何结合动态数量(150-200)的异步函数进行计算
【发布时间】:2021-10-05 18:19:31
【问题描述】:

目前正在开展一个项目,该项目使用 Binance Websockets 获取硬币价格数据并使用数据进行计算。

我计算的硬币数量是动态的(从 150 到 ~250 不等)。

ASYNC 函数调用calculate(client, queue, coin)

它采用以下参数:

  1. 客户端:币安异步客户端(python-binance 库)
  2. 队列:如果计算结果为正,则机会进入队列
  3. coin:硬币,例如比特币

calculate 函数包含一个while 1(不定式)循环,因此计算会继续运行。

目前main 函数使用 asyncio.gather 来组合不同硬币 (150 - ~250) 的计算函数

async def main(queue):

await asyncio.gather(
    calculate(client, queue, 'BTC'),
    calculate(client, queue, 'ETH'),
    calculate(client, queue, 'BNB'),
    calculate(client, queue, 'LINK'),
    calculate(client, queue, 'SHIB'),
    calculate(client, queue, 'ADA'),
    calculate(client, queue, 'XRP'),
    calculate(client, queue, 'VET')
    # This continues for the the other +100 coins
    )


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(queue))

这不是一种编写代码的好方法,如果我想换硬币,效率很低。 我使用 API 获取需要计算的硬币。 所以我需要手动更新 100+ 行调用每个硬币的函数并更新一些其他文件以确保一切运行顺利。

什么是解决这个问题的好方法?

我见过 asyncio 的线程/多线程/更复杂的用法,但我不知道如何将它应用到这个问题上。

我们将不胜感激。

【问题讨论】:

    标签: python multithreading websocket python-asyncio python-multithreading


    【解决方案1】:

    您想创建一个硬币列表以调用calculate(),使用该列表创建一个计算列表,然后使用一个带星号的表达式将该列表解压缩为asyncio.gather() 的参数:

    async def main(queue):
        coins = ['BTC', 'ETH', 'BNB']  # Add more coins as desired.
        calculations = [calculate(client, queue, coin) for coin in coins]
    
        await asyncio.gather(*calculations)  # Use a starred expression to unpack the list.
    
    
    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main(queue))
    

    【讨论】:

    • 谢谢你!这帮助很大。
    • 你认为 asyncio gather 是在这里使用的最佳方法吗?
    • @T.deJong 我没有经常使用asyncio,所以我不确定gather() 是否是你正在做的最好的方法。但这里有一篇关于 wait()gather() 之间差异的帖子,可能会有所帮助:stackoverflow.com/questions/42231161/…
    • 好的,这提供了对差异的更多见解,谢谢!您是否有过(多)踩踏经验,如果有,在这里使用会更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多