开发者

What is the proper method of printing Python Exceptions?

        except ImportError as xcpt:
      开发者_开发技巧      print "Import Error: " + xcpt.message

Gets you a deprecation warning in 2.6 because message is going away. Stackoverflow

How should you be dealing with ImportError? (Note, this is a built-in exception, not one of my making....)


The correct approach is

xcpt.args

Only the message attribute is going away. The exception will continue to exist and it will continue to have arguments.

Read this: http://www.python.org/dev/peps/pep-0352/ which has some rational for removing the messages attribute.


If you want to print the exception:

print "Couldn't import foo.bar.baz: %s" % xcpt

Exceptions have a __str__ method defined to create a readable version of themselves. I wouldn't bother with "Import Error:" since the exception will provide that itself. If you add text to the exception, make it be something you know based on the code you were trying to execute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜