2010-10-03 193 views
1

使用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 

是不是名博客错误DEFI由PyBlog所定义,因为那是我第一次得到这个名字的地方?我使用“except”错误吗?感谢您的任何提示!

回答

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对象做的同样的规则。

+0

谢谢,我真的需要刷新我的范围。感谢帮助! – 2010-10-03 22:36:58

2

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

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

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

谢谢!我真的很感谢答案。 – 2010-10-03 22:36:34

2

代码会

from pyblog import BlogError