异常中的Python字符串转换为元组

时间:2016-06-21 08:50:48

标签: python string exception tuples

Python 2.7.10似乎在抛出异常时将我的字符串转换为元组。这是我的例子:

class MyError(RuntimeError):
   def __init__(self, arg):
      self.args = arg

def raiseMyError():
    errorCode = 29
    errorText = 'Port not ready yet'
    exitCodeMessage = 'ERROR {0}: {1}'.format(errorCode, errorText)
    # print exitCodeMessage  --> print out here and it's a string
    raise MyError(str(exitCodeMessage))

try:
    raiseMyError()

except MyError as e:
    print e.args

我创建了一个包含错误代码和描述的字符串,并使用它来构造一个专门构建的异常类。当我在创建异常之前打印出exitCodeMessage变量时,我得到了我期望的结果:

ERROR 29: Port not ready yet

但是,异常处理程序中的跟踪给出了以下内容:

('E', 'R', 'R', 'O', 'R', ' ', '2', '9', ':', ' ', 'P', 'o', 'r', 't', ' ', 'n', 'o', 't',
' ', 'r', 'e', 'a', 'd', 'y', ' ', 'y', 'e', 't')

谁能告诉我这里发生了什么以及我能做些什么呢?

2 个答案:

答案 0 :(得分:2)

实际上你根本不需要覆盖__init__方法,这足以:

class MyError(RuntimeError):
   pass

关于args的行为 - docs状态:

  

赋予异常构造函数的参数元组。

当您继承Exception课程或其中任何一个孩子时,打印e.args只会打印tuple(e.args),因为args属性是以{{1}的方式定义的class(参见@ advance512的答案)。

如果您不从Exception继承:

Exception

你没有继承class MyError: def __init__(self, arg): self.args = arg 背后的“魔法”,因此调用args将按预期工作。

你也可以这样写(注意 self.arg 而不是 self.args ):

e.args

并且调用class MyError(RuntimeError): def __init__(self, arg): self.arg = arg 也将按预期工作。

答案 1 :(得分:2)

这是因为args是BaseException类中定义的属性。

查看exceptions.py:70:

args = property(lambda self: tuple())

试试这个:

class MyError(RuntimeError):
   def __init__(self, errorString):
      self._errorString = errorString

def raiseMyError():
    errorCode = 29
    errorText = 'Port not ready yet'
    exitCodeMessage = 'ERROR %s: %s' % (errorCode, errorText)
    # print exitCodeMessage  --> print out here and it's a string
    raise MyError(exitCodeMessage)

try:
    raiseMyError()

except MyError as e:
    print e._errorString
    print e.args

输出:

ERROR 29: Port not ready yet
()