-1

I wrote a Python script to check my email and turn on an LED when I have new mail. After about 1 hour, I got the error:

Traceback (most recent call last):
  File "checkmail.py", line 10, in <module>
   B = int(feedparser.parse("https://" + U + ":" + P + "@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
  File "/usr/local/lib/python2.7/dist-packages/feedparser.py", line 375, in __getitem__
    return dict.__getitem__(self, key)
KeyError: 'fullcount'

I looked here and didn't find an answer. Here is my code:

#!/usr/bin/env python
import RPi.GPIO as GPIO, feedparser, time
U = "username"
P = "password"
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
A = 23
GPIO.setup(A, GPIO.OUT)
while True:
        B = int(feedparser.parse("https://" + U + ":" + P + "@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
        if B > 0:
                GPIO.output(A, True)
        else:
                GPiO.output(A, False)
        time.sleep(60)

I'm running this on a Raspberry Pi. Thanks in advance for any help.

4

1 回答 1

1

您需要添加一些调试代码并查看此调用返回的内容:

feedparser.parse("https://" + U + ":" + P + "@mail.google.com/gmail/feed/atom")["feed"]

这显然是不包含“fullcount”项目的东西。你可能想做这样的事情:

feed = feedparser.parse("https://{}:{}@mail.google.com/gmail/feed/atom".format(U, P))
try:
    B = int(feed["feed"]["fullcount"])
except KeyError:
    # handle the error
    continue  # you might want to sleep or put the following code in the else block

这样您就可以处理错误(您可能也想捕获ValueError,以防int()由于无效值而失败)而不会破坏您的脚本。

于 2013-12-29T23:39:20.827 回答