以平台无关的方式处理Windows特定的异常 [英] Handling Windows-specific exceptions in platform-independent way

查看:48
本文介绍了以平台无关的方式处理Windows特定的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Python异常:

Consider the following Python exception:

  [...]
    f.extractall()
  File "C:\Python26\lib\zipfile.py", line 935, in extractall
    self.extract(zipinfo, path, pwd)
  File "C:\Python26\lib\zipfile.py", line 923, in extract
    return self._extract_member(member, path, pwd)
  File "C:\Python26\lib\zipfile.py", line 957, in _extract_member
    os.makedirs(upperdirs)
  File "C:\Python26\lib\os.py", line 157, in makedirs
    mkdir(name, mode)
WindowsError: [Error 267] The directory name is invalid: 'C:\\HOME\\as\
\pypm-infinitude\\scratch\\b\\slut-0.9.0.zip.work\\slut-0.9\\aux'

我想处理这个特殊的异常-即WindowsError,错误号为267.但是,我不能简单地执行以下操作:

I want to handle this particular exception - i.e., WindowsError with error number 267. However, I cannot simply do the following:

try:
    do()
except WindowsError, e:
    ...

因为这在Unix系统中甚至在异常模块中都没有定义WindowsError的情况下不起作用.

Because that would not work on Unix systems where WindowsError is not even defined in the exceptions module.

是否有一种优雅的方式来处理此错误?

Is there an elegant way to handle this error?

推荐答案

这是我当前的解决方案,但是我在except块中使用非平凡的代码略为鄙视:

Here's my current solution, but I slightly despise using non-trivial code in a except block:

        try:
            f.extractall()
        except OSError, e:
            # http://bugs.python.org/issue6609
            if sys.platform.startswith('win'):
                if isinstance(e, WindowsError) and e.winerror == 267:
                    raise InvalidFile, ('uses Windows special name (%s)' % e)
            raise

这篇关于以平台无关的方式处理Windows特定的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆