处理Python脚本中的错误

时间:2010-10-03 14:08:37

标签: python xml wordpress

使用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定义的博客错误名称,因为那是我首先获得该名称的地方吗?我用“除了”错了吗?感谢您的任何提示!

3 个答案:

答案 0 :(得分:5)

是的,它正在使用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对象相同的范围规则。

答案 1 :(得分:2)

您的except在语法上是正确的。然而它失败了,因为你没有明确地将BlogError异常类导入到程序的命名空间中。

要解决此问题,请明确导入BlogError类。对于例如

from pyblog import BlogError
try:
    ...
except BlogError:
    ...

答案 2 :(得分:2)

代码将是

 from pyblog import BlogError
相关问题