KeyError:邮件脚本中的'fullcount'

时间:2013-12-29 23:37:48

标签: python parsing email raspberry-pi keyerror

我写了一个Python脚本来查看我的电子邮件,并在我收到新邮件时打开LED。 大约1小时后,我收到错误:

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'

我看了here 并没有找到答案。这是我的代码:

#!/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)

我在Raspberry Pi上运行它。 提前感谢您的帮助。

1 个答案:

答案 0 :(得分: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()由于值无效而失败)而不会炸毁你的脚本。