代码之家  ›  专栏  ›  技术社区  ›  Michael Morisy

处理python脚本中的错误

  •  1
  • Michael Morisy  · 技术社区  · 15 年前

    使用 pyblog.py ,我得到了以下错误,然后我尝试更优雅地处理这些错误:

    Traceback (most recent call last):
      File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript
        exec codeObject in __main__.__dict__
      File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 11, in <module>
        date = blogurl.get_recent_posts(1)[0]['dateCreated']
      File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 129, in get_recent_posts
        return self.execute('metaWeblog.getRecentPosts', blogid, self.username, self.password, numposts)
      File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 93, in execute
        raise BlogError(fault.faultString)
    BlogError: XML-RPC services are disabled on this blog.  An admin user can enable them at http://example.com/blogname/wp-admin/options-writing.php
    >>> 
    

    所以我尝试了以下代码,但没有破坏脚本:

    for blog in bloglist:
        try:
            blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24')
            date = blogurl.get_recent_posts(1)[0]['dateCreated']
            print blog + ', ' + str(date.timetuple().tm_mon) + '/' + str(date.timetuple().tm_mday) + '/' + str(date.timetuple().tm_year)
        except BlogError:
            print "Oops! The blog at " + blogurl + " is not configured properly."
    

    仅获取以下错误:

    Traceback (most recent call last):
      File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript
        exec codeObject in __main__.__dict__
      File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 13, in <module>
        except BlogError:
    NameError: name 'BlogError' is not defined
    

    不是pyblog定义的name blog错误吗,因为我是从那里得到这个名字的?我用“except”是错的吗?谢谢你的建议!

    3 回复  |  直到 15 年前
        1
  •  5
  •   Mike Axiak    15 年前

    是的,它正在使用blogerror,但您尚未将blogerror导入到命名空间中以供引用。相反,您希望使用pyblog.blogerror:

    for blog in bloglist:
        try:
            blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24')
            date = blogurl.get_recent_posts(1)[0]['dateCreated']
            print blog + ', ' + str(date.timetuple().tm_mon) + '/' + str(date.timetuple().tm_mday) + '/' + str(date.timetuple().tm_year)
        except pyblog.BlogError:
            print "Oops! The blog at " + blogurl + " is not configured properly."
    

    请记住,异常遵循与任何Python对象相同的作用域规则。

        2
  •  2
  •   Manoj Govindan    15 年前

    你的 except 语法正确。但它失败了,因为您没有显式导入 BlogError 异常类进入程序的命名空间。

    要解决此问题,请显式导入 博客错误 班级。例如

    from pyblog import BlogError
    try:
        ...
    except BlogError:
        ...
    
        3
  •  2
  •   jknair    15 年前

    代码将是

     from pyblog import BlogError