2012-03-31 52 views
4

在Python 2.7,你可以做到這一點,看看例外列表:有沒有辦法在Python 3.x中獲得可能的異常列表?

import exceptions 

    for i in dir(exceptions): 
    print (i) 

有沒有爲Python 3.2類似的東西?有一件事情沒有模塊「例外」。我知道你可以遍歷Exception,但是這並不能給你列出所有可能的異常,這就是我正在尋找的。

+0

(沒有固定的例外;新的可以定義) – 2012-03-31 01:18:59

回答

3

你可以做這樣的事情(不漂亮,但工程),以獲得內建的例外列表:

>>> exes = [ex for ex in vars(__builtins__).values() 
...   if hasattr(ex, '__mro__') and issubclass(ex, BaseException)] 
>>> exes 
[<class 'IndexError'>, <class 'SyntaxError'>, <class 'UnicodeDecodeError'>, 
<class 'NameError'>, <class 'BytesWarning'>, <class 'IOError'>, <class 'SystemExit'>, 
<class 'RuntimeWarning'>, <class 'Warning'>, <class 'UnicodeTranslateError'>, 
<class 'EOFError'>, <class 'BufferError'>, <class 'FloatingPointError'>, 
<class 'FutureWarning'>, <class 'ImportWarning'>, <class 'ReferenceError'>, 
<class 'TypeError'>, <class 'KeyboardInterrupt'>, <class 'UserWarning'>, 
<class 'ResourceWarning'>, <class 'SystemError'>, <class 'BaseException'>, 
<class 'RuntimeError'>, <class 'MemoryError'>, <class 'StopIteration'>, 
<class 'LookupError'>, <class 'UnicodeError'>, <class 'ImportError'>, 
<class 'Exception'>, <class 'UnicodeEncodeError'>, <class 'SyntaxWarning'>, 
<class 'ArithmeticError'>, <class 'GeneratorExit'>, <class 'KeyError'>, 
<class 'PendingDeprecationWarning'>, <class 'EnvironmentError'>, <class 'OSError'>, 
<class 'DeprecationWarning'>, <class 'UnicodeWarning'>, <class 'ValueError'>, 
<class 'TabError'>, <class 'ZeroDivisionError'>, <class 'IndentationError'>, 
<class 'AssertionError'>, <class 'UnboundLocalError'>, <class 'NotImplementedError'>, 
<class 'AttributeError'>, <class 'OverflowError'>] 
2

這絕對不是一個好的解決方案,但它挺酷的。

>>> from urllib.request import urlopen 
>>> from bs4 import BeautifulSoup 
>>> 
>>> data = urlopen('http://docs.python.org/py3k/library/exceptions.html').read() 
>>> parsed = BeautifulSoup(data) 
>>> exceptions = [x.text for x in parsed.select('dl.exception > dt tt.descname')] 
>>> exceptions 
['BaseException', 'Exception', 'ArithmeticError', 'BufferError', 'LookupError', 
'EnvironmentError', 'AssertionError', 'AttributeError', 'EOFError', 
'FloatingPointError', 'GeneratorExit', 'IOError', 'ImportError', 'IndexError', 
'KeyError', 'KeyboardInterrupt', 'MemoryError', 'NameError', 'NotImplementedError', 
'OSError', 'OverflowError', 'ReferenceError', 'RuntimeError', 'StopIteration', 
'SyntaxError', 'IndentationError', 'TabError', 'SystemError', 'SystemExit', 
'TypeError', 'UnboundLocalError', 'UnicodeError', 'UnicodeEncodeError', 
'UnicodeDecodeError', 'UnicodeTranslateError', 'ValueError', 'VMSError', 
'WindowsError', 'ZeroDivisionError', 'Warning', 'UserWarning', 'DeprecationWarning', 
'PendingDeprecationWarning', 'SyntaxWarning', 'RuntimeWarning', 'FutureWarning', 
'ImportWarning', 'UnicodeWarning', 'BytesWarning', 'ResourceWarning'] 

(需要BeautifulSoup 4

+0

這兩項的做什麼,我一直在尋找,一點點額外的垃圾,我能活用。謝謝! – cyd 2012-03-31 20:44:14

+0

@cyd,另一個答案更好:它不涉及抓取HTML。 – huon 2012-04-01 03:17:13

相關問題