首页 > 解决方案 > 为什么这个程序调用了错误的方法?[Python, MultiTimer 库]

问题描述

我在尝试按如下方式构建代码时遇到了一个奇怪的问题:

一开始,程序开始重复n multi timers调用方法m_1m_n每一秒。t_1t_n

为了实现这一点,我使用了 MultiTimer 库 ( https://pypi.org/project/multitimer/ )。为了灵活性,我在包含该方法的程序的开头定义了一个命名元组,无论它是否启用以及调用它的频率。

我认为问题在于我如何使用命名元组,但我似乎无法弄清楚问题所在。

BotSettings = namedtuple(
    "BotSettings", ["method", "enabled", "repeat_every_x_seconds"])
bot_list = [
    BotSettings(method=bots.accept_pending_invites,
                enabled=True, repeat_every_x_seconds=10),
    BotSettings(method=bots.handle_cat_requests,
                enabled=True, repeat_every_x_seconds=10),
    BotSettings(method=bots.handle_confession_requests,
                enabled=True, repeat_every_x_seconds=10)
]
timers = [MultiTimer(bot.repeat_every_x_seconds, lambda: bot.method(
        client), runonstart=True) for bot in bot_list if bot.enabled]
for timer in timers:
    timer.start()

上述程序的输出如下:

handle confession requests called
handle confession requests called
handle confession requests called

我所做的另一个观察是,程序总是在bot_list num_enabled其中num_enabled方法数为bot_listwith的时间调用最后一个方法enabled=True

标签: pythonmultithreadingtimer

解决方案


用函数替换 lambda 并使用 kwargs 传递参数。我使用此代码进行测试。

from multitimer import MultiTimer

def accept_pending_invites(client): print('invite', client)
def handle_cat_requests(client): print('cat', client)
def handle_confession_requests(client): print('confess', client)

bot_list=[
{ 'method':accept_pending_invites, 'enabled':True, 'repeat_every_x_seconds':10},
{ 'method':handle_cat_requests,'enabled':True, 'repeat_every_x_seconds':10},
{ 'method':handle_confession_requests, 'enabled':True, 'repeat_every_x_seconds':10}
]

timers = [MultiTimer(bot['repeat_every_x_seconds'], function=bot['method'], runonstart=True, kwargs={'client':123}) for bot in bot_list]
for timer in timers:
    timer.start()

输出

invite 123
cat 123
confess 123

推荐阅读