Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 威利机器人-解析rss并检查新帖子_Python_Bots_Irc - Fatal编程技术网

Python 威利机器人-解析rss并检查新帖子

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

我正在为我的威利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].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