可能重复:
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模块,但它不起作用。
>>> import json
>>> errors = out.split(":")[-1]
>>> my_list = json.loads(errors)
我得到了这个例外:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
请您建议一些方法来调整代码以获得我想要的内容吗?
编辑:添加了用例。
我的问题适用的背景是:
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']"
答案 0 :(得分:4)
您应该使用:
import ast
ls="['a','b','c']"
ast.literal_eval(ls)
Out[178]: ['a', 'b', 'c']
或作为一个完整的:
In [195]: ast.literal_eval(out.split(':')[1])
Out[195]: [u'Error 1', u'Another error']
答案 1 :(得分:1)
看起来你试图打印异常;您可以使用.args
参数访问异常的参数:
print exc.args[0]