【问题标题】:KeyError: 'fullcount' in mail scriptKeyError:邮件脚本中的“fullcount”
【发布时间】:2013-12-29 23:37:47
【问题描述】:

我编写了一个 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)

我在树莓派上运行它。 提前感谢您的帮助。

【问题讨论】:

    标签: python parsing email raspberry-pi keyerror


    【解决方案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() 由于无效值而失败)而不会破坏您的脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2018-12-29
      • 2013-01-19
      • 1970-01-01
      • 2014-05-25
      • 2018-11-13
      相关资源
      最近更新 更多