python - 为什么这个程序调用了错误的方法?[Python, MultiTimer 库]
问题描述
我在尝试按如下方式构建代码时遇到了一个奇怪的问题:
一开始,程序开始重复n
multi timers
调用方法m_1
到m_n
每一秒。t_1
t_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_list
with的时间调用最后一个方法enabled=True
。
解决方案
用函数替换 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
推荐阅读
- python - 格式化数据以在 Streamplot 中使用
- webpack - Webpack LESS-loader 意外的字符错误
- playback - 如何处理“Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互”。在带有 Chrome 64 的桌面上?
- angular - 以角度 4 阻止多个文件选择和上传
- gnuplot - 如何在gnuplot中以指定间隔显示标记?
- python - 如何将传感器读数从 raspi 存储到我的数据库中?
- android - Android GeoLocation FireStore:一种在用户关闭位置共享选项后阻止谷歌服务获取用户地理点的方法
- angular - Angular 5 ngx-toastr 不显示 html 消息
- excel - 如何匹配来自多个数据集的多行?
- apache-kafka - 卡夫卡授权