Python 威利机器人-解析rss并检查新帖子
我正在为我的威利irc机器人做一个模块,每当论坛上的一个给定线程中出现一篇新帖子时,这个机器人就会说一条消息。实际上,我遇到的问题很奇怪:bot每隔一段时间就会返回一个未处理的异常:Python 威利机器人-解析rss并检查新帖子,python,bots,irc,Python,Bots,Irc,我正在为我的威利irc机器人做一个模块,每当论坛上的一个给定线程中出现一篇新帖子时,这个机器人就会说一条消息。实际上,我遇到的问题很奇怪:bot每隔一段时间就会返回一个未处理的异常: Unhandled exception in thread started by <function lurk at 0x10ebfa8c0> Traceback (most recent call last): line 27, in lurk d=c.entries[0].publish
Unhandled exception in thread started by <function lurk at 0x10ebfa8c0>
Traceback (most recent call last):
line 27, in lurk
d=c.entries[0].published
IndexError: list index out of range
我的第一个想法是,10秒钟的睡眠不足以让我的机器人解析rss。这里有没有人根据他们的经验知道什么时间是100%安全的
第二个想法是忽略错误,创建一个异常,它不做任何事情,不阻止循环,只重试整个过程。这样行吗
try:
#here goes the while loop
except:
Pass
你认为哪个选项更好?我希望最终以“专业”的方式开始编码,而不是让noob工作。如果你有自己的想法,请说出来
谢谢 如果
d.entries
列表中没有项目,则会发生此错误。例如,在您的控制台中:
>>> entries = []
>>> entries[0]
... IndexError: list index out of range
要避免此错误,只需在继续之前检查是否找到条目。例如,您可以将循环更改为以下内容:
while True:
time.sleep(10)
c=feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')
if not c.entries:
# no entries found, re-enter the loop at the "sleep"
continue
# entries found, process them...
注意,我已将
sleep
移到顶部您的问题似乎是feedparser.parse
没有返回任何条目。我不会将整个while循环包装在try-except语句中,而是确保返回0个以上的条目
我将替换feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175”)
在while循环中使用以下命令:
import logging
...
c = feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')
if not len(c.entries):
# You can use your own logger instance instead
# Log any information you need to identify the real problem
logging.error("No entries found: %s", str(c))
continue
这将防止您获得异常,并具有记录信息的额外优势,以便您可以确定为什么没有获得任何条目
您也可以对您的
feedparser执行相同的操作。在while循环之外解析continue
调用,只需将continue
替换为return很抱歉,但是FastTurl的答案更有用。不过,我已经使用了您的建议,将sleep
移动到顶部,因此我将给您一个+1:)这是作为str(c)
:{feed':{},'bozo':1,'bozo_异常]:URLError(超时('timed out',),,,,'entries':[]
所以我想这不是我的错,而且是真的?看来你对此无能为力。但是现在这个问题不应该破坏你的程序。您可以查看有关bozo\u异常的更多信息
。
import logging
...
c = feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')
if not len(c.entries):
# You can use your own logger instance instead
# Log any information you need to identify the real problem
logging.error("No entries found: %s", str(c))
continue