处理Python脚本中的错误

Mic*_*isy 1 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
>>> 
Run Code Online (Sandbox Code Playgroud)

所以我尝试了以下代码,而不会崩溃脚本:

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."
Run Code Online (Sandbox Code Playgroud)

只是为了得到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

是不是通过PyBlog定义的名称博客错误,因为这就是我的第一个地方,叫什么名字?我用"除了"错了吗?谢谢你的任何提示!

Mik*_*iak 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."
Run Code Online (Sandbox Code Playgroud)

请记住,异常遵循与任何python对象相同的范围规则.