0

フォーラムの特定のスレッドに新しい投稿が表示されるたびにボットにメッセージを送信させる、willie irc ボットのモジュールを作成しています。私が遭遇した問題は、実際には非常に奇妙です: ボットは時々未処理の例外を返します:

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

エラーはランダムに表示されます。通常は約 30 分ですが、1.5 時間のセッション全体でまったく表示されなかったことがありました。これをどのように処理すべきかについていくつかのアイデアがありますが、最初にコードの一部を見てみましょう。

import willie
import time
import thread
import feedparser
...
@willie.module.commands('startlurking')
def startlurking(bot, trigger):
    def lurk():
        bot.say("Right away, sir.")
        a=feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')
        b=a.entries[0].published
        while True:
            c=feedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')
            d=c.entries[0].published #this is the line 27
            if not d==b:
                bot.say(trigger.nick + ", I have spotted a new post!")
                bot.say(c.entries[0].link)
                bot.say(c.entries[0].description)
                b=d
            time.sleep(10)

    thread.start_new_thread(lurk, ())

私の最初の考えは、ボットが RSS を解析するには 10 秒のスリープでは不十分だということです。経験から、ここで 100% 安全な時間の長さを知っている人はいますか?

2番目のアイデアは、エラーを無視して、何もせず、ループを中断せず、すべてを再試行する例外を作成することです。これは機能しますか?

try:
    #here goes the while loop
except:
    Pass

あなたの意見では、どのオプションがより良いですか? 最終的には「プロ」の方法でコーディングを開始し、noob の回避策を作成したくありません。自分の考えがあれば、それを言ってください。

ありがとう!

4

2 に答える 2

1

このエラーは、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トップに移動しましたのでご注意ください

于 2013-08-02T19:35:42.657 に答える
0

あなたの問題は、feedparser.parseエントリが返されていないようです。while ループ全体を try except ステートメントでラップする代わりに、1 つ以上のエントリが返されるようにします。

while ループを次のように置き換えfeedparser.parse('http://forums.wesnoth.org/feed.php?t=39175')ます。

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.parsewhile ループの外で呼び出しに対して同じことを行うこともできcontinueますreturn

于 2013-08-02T19:36:36.133 に答える