Python异常类未定义,没有属性

时间:2017-05-16 21:53:23

标签: python exception exception-handling

我目前正在使用pytesseract,它定义了一个异常类,如下所示:

class TesseractError(Exception):
    def __init__(self, status, message):
        self.status = status
        self.message = message
        self.args = (status, message)

在我的main.py中,我尝试了几种方法来使用此异常进行异常处理,但我没有“TesseractError”属性错误且没有“TesseractError”定义错误。

1

>>> from pytesseract import TesseractError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'TesseractError'

2

>>> import pytesseract
>>> try: raise pytesseract.TesseractError(True,"True")
... except TesseractError: print("error")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'pytesseract' has no attribute 'TesseractError'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'TesseractError' is not defined

3

>>> import pytesseract
>>> try: raise TesseractError(True,"True")
... except TesseractError: print("error")
...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'TesseractError' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'TesseractError' is not defined

但是,当我在终端中尝试以下操作时,它才能正常工作。

>>> class ERR(Exception): pass
>>> try: raise ERR()
... except ERR: print("error found")
error found

所以似乎导入步骤是错误的,但我不知道是什么导致它。

1 个答案:

答案 0 :(得分:1)

这是__init__文件:

https://github.com/madmaze/pytesseract/blob/master/src/init.py

请注意,它不会导致TesseractError从包本身可见。您可以更改 init 文件,也可以从包&gt;模块&gt;中导入。

from pytesseract.pytesseract import TesseractError