Skip to main content
 首页 » 编程设计

python之处理 Python 脚本中的错误

2025年05月04日9zdz8207

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

请您参考如下方法:

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