【问题标题】:How to multiprocess async/await functions in python?如何在 python 中多处理 async/await 函数?
【发布时间】:2021-04-11 22:10:08
【问题描述】:

我需要每 60 秒为我的所有汽车举办一次活动。我对下面代码的问题是while循环直到超时(60)才结束,因此只有汽车中的第一辆车在运行。

class RunCars(BaseEvent):

    def __init__(self):
        interval_seconds = 60  # Set the interval for this event
        super().__init__(interval_seconds)

    # run() method will be called once every {interval_seconds} minutes
    async def run(self, client, cars):
        for car in cars:        
            channel = get_channel(client, "general")
            await client.send_message(channel, 'Running this '+str(car))
            await msg.add_reaction(str(get_emoji(':smiley:'))) 
            
            reaction = None
            while True:
                if str(reaction) == str(get_emoji(':smiley:'))
                    await client.send_message(channel, 'Finished with this '+str(car))
                try:
                    reaction, user = await client.wait_for('reaction_add', timeout=60, check=check)
                except:
                    break

我尝试将代码更改为多线程进程,但在函数内部的 async/await 和 pickle 函数本身存在问题。

如果您有任何关于如何解决此问题的建议,我将不胜感激。

【问题讨论】:

    标签: python python-3.x async-await python-asyncio python-multiprocessing


    【解决方案1】:

    asyncio 模块允许您使用gather 方法同时执行多个async 方法。我认为您可以通过定义一个运行单个汽车的方法来实现您想要的行为,然后将您的for-loop 替换为对gather 的调用,这将同时执行多个run_one 协程(方法):

    import asyncio
    
    class RunCars(BaseEvent):
    
        def __init__(self):
            interval_seconds = 60  # Set the interval for this event
            super().__init__(interval_seconds)
    
    
        async def run(self, client, cars):
            coroutines = [self.run_one(client, car) for car in cars]
            asyncio.gather(*coroutines)
    
        async def run_one(self, client, car):
            channel = get_channel(client, "general")
            await client.send_message(channel, 'Running this '+str(car))
            await msg.add_reaction(str(get_emoji(':smiley:'))) 
              
            reaction = None
            while True:
                if str(reaction) == str(get_emoji(':smiley:'))
                    await client.send_message(channel, 'Finished with this '+str(car))
                try:
                    reaction, user = await client.wait_for('reaction_add', timeout=60, check=check)
                except:
                    break
    

    一般来说,在编写异步代码时,您应该尝试用gather 语句替换对async 方法的顺序调用(基本上是调用async 方法的for-循环),以便它们同时执行。

    【讨论】:

    • 我原则上同意,但这个答案并没有解释为什么他的代码不起作用。诚然,这很难说,因为问题应该更加集中。因为它意味着太多方面
    • @mackorone 非常感谢您的回答。这就是我想弄清楚的。 stackoverflow 变成了如此消极的地方,这真的很糟糕。有些人认为它需要以特定的方式工作,事实从未如此明显
    • @Pynchia 是的,我不打算解释 asyncio 只是为了回答这个问题。还有 echan00,很乐意为您提供帮助!
    猜你喜欢
    • 2020-09-22
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2019-07-06
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多