Python:只发送前缀时,IRC僵尸程序崩溃

时间:2015-03-04 06:53:19

标签: python bots irc

当我只发送前缀(!)

时,我有一个崩溃的IRC机器人

我明白为什么会发生这种情况,但我无法弄清楚如何让它忽略而不是杀死它。

来源:https://github.com/SamWilber/rollbot/blob/master/rollbot.py

错误:

:turtlemansam!~turtleman@unaffiliated/turtlemansam PRIVMSG #tagprobots :!
Traceback (most recent call last):
line 408, in <module>
    bot.connect()
line 81, in connect
    self.run_loop()
line 117, in run_loop
    self.handle_message(source_nick, message_dict['destination'], message_dict['message'])
in handle_message
    self.handle_command(source, destination, message)
line 139, in handle_command
    command_key = split_message[0].lower()
IndexError: list index out of range

1 个答案:

答案 0 :(得分:1)

罪魁祸首是该片段:

def handle_command(self, source, destination, message):
    split_message = message[1:].split()
    command_key = split_message[0].lower() # L139
    …

这是因为当你只发送前缀时,没有&#34;右手边&#34;前缀后的部分。因此,当您尝试拆分不存在的RHS部件时,它等同于执行以下操作:

>>> "".split()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

不好,呃?

因此,解决方案是在此阶段添加异常处理:

try:
    split_message = message[1:].split()
    command_key = split_message[0].lower()
except IndexError:
    print("No Command")
    return
…

但是,我的个人偏好是检查split_message的长度,因为这不是例外行为,而是可能的用例场景:

split_message = message[1:].split()
if len(split_message) is 0:
    print("No Command")
    return
else:
    command_key = split_message[0].lower()
    …

在python中,异常被认为是无成本的(就内存/处理器开销而言),因此通常会鼓励它们的使用。

但是,如果我的偏好结束而不是在这种情况下使用例外,那是因为:

  • 当你编写一个算法时,总是要在执行流程中集成用例的可能性,而不是打破执行流程(这就是一个做法),因为它提高了代码的可读性......
  • 它避免了影响另一个异常的可能性。

HTH

相关问题