Python 以独立于平台的方式处理特定于Windows的异常
考虑以下Python异常:Python 以独立于平台的方式处理特定于Windows的异常,python,windows,exception,exception-handling,Python,Windows,Exception,Exception Handling,考虑以下Python异常: [...] 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)
[...]
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'
我想处理这个特殊的异常,即错误号为267的WindowsError。然而,我不能简单地做到以下几点:
try:
do()
except WindowsError, e:
...
因为这在Unix系统上不起作用,因为Windows错误甚至没有在exceptions模块中定义
有没有一种优雅的方法来处理这个错误?这是我目前的解决方案,但我有点不喜欢在except块中使用非平凡的代码:
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
以下是我当前的解决方案,但我有点不喜欢在except块中使用非平凡代码:
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
如果需要捕获名称可能不总是存在的异常,请创建它:
if not getattr(__builtins__, "WindowsError", None):
class WindowsError(OSError): pass
try:
do()
except WindowsError, e:
print "error"
如果您在Windows上,您将使用真实的WindowsError类并捕获异常。如果没有,您将创建一个永远不会引发的WindowsError类,这样except子句不会导致任何错误,并且except子句永远不会被调用。如果您需要捕获一个名称可能不总是存在的异常,请创建它:
if not getattr(__builtins__, "WindowsError", None):
class WindowsError(OSError): pass
try:
do()
except WindowsError, e:
print "error"
如果您在Windows上,您将使用真实的WindowsError类并捕获异常。如果没有,您将创建一个永远不会引发的WindowsError类,因此except子句不会导致任何错误,并且永远不会调用except子句。@Glenn Maynard的回答不允许使用pdb进行调试,因为WindowsError内置项在调试器中不可用。此代码块将在Python调试器内部和正常执行期间工作:
import exceptions
if not getattr(exceptions, "WindowsError", None):
class WindowsError(OSError): pass
此解决方案还可以工作,并避免字符串文字和导入完整异常库:
try:
from exceptions import WindowsError
except ImportError:
class WindowsError(OSError): pass
@Glenn Maynard的回答不允许使用pdb进行调试,因为WindowsError内置在调试器中不可用。此代码块将在Python调试器内部和正常执行期间工作:
import exceptions
if not getattr(exceptions, "WindowsError", None):
class WindowsError(OSError): pass
此解决方案还可以工作,并避免字符串文字和导入完整异常库:
try:
from exceptions import WindowsError
except ImportError:
class WindowsError(OSError): pass
cf.cf.请注意
异常
库是Python 2而不是Python 3请注意异常
库是Python 2而不是Python 3