从表示lis的字符串创建列表

2024-04-26 01:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How do I parse a string representing a nested list into an actual list?

如何从这个字符串中获取错误列表?在

>>> out = "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"

我试着使用json模块,但是没有用。在

^{pr2}$

我有个例外:

^{3}$

你能建议一些方法来调整代码以得到我想要的吗?在

编辑:添加用例。

我的问题适用的背景是:

try:
    # some code generating an xmlrpclib.Fault exception
    pass
except xmlrpclib.Fault, err:
    # here print dir(err) gives:
    # ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
    # '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
    # '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
    # '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
    # '__unicode__', '__weakref__', 'args', 'faultCode', 'faultString', 'message']

    exit(err.faultString)
    # exits with: "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"

Tags: anapireduceanothererrorlistclassexceptions
2条回答

您应该使用:

import ast

ls="['a','b','c']"

ast.literal_eval(ls)
Out[178]: ['a', 'b', 'c']

或者作为一个完整的:

^{pr2}$

看起来您试图打印异常;您可以使用.args参数访问异常的参数

print exc.args[0]

相关问题 更多 >