Rei*_*ica 8 python windows exception-handling exception
考虑以下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)
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'
Run Code Online (Sandbox Code Playgroud)
我想处理这个特殊的异常 - 即,错误号为267的WindowsError.但是,我不能简单地执行以下操作:
try:
do()
except WindowsError, e:
...
Run Code Online (Sandbox Code Playgroud)
因为这在Unix系统上不起作用,因为在异常模块中甚至没有定义WindowsError.
有一种优雅的方法来处理这个错误吗?
Gle*_*ard 13
如果需要使用可能并不总是存在的名称捕获异常,请创建它:
if not getattr(__builtins__, "WindowsError", None):
class WindowsError(OSError): pass
try:
do()
except WindowsError, e:
print "error"
Run Code Online (Sandbox Code Playgroud)
如果你在Windows上,你将使用真正的WindowsError类并捕获异常.如果不是,您将创建一个永远不会引发的WindowsError类,因此except子句不会导致任何错误,并且永远不会调用except子句.
这是我当前的解决方案,但是我在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7552 次 |
| 最近记录: |