从Python 2.6开始,你可以使用内置的
ast.literal_eval:
>>> import ast>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}"){'muffin': 'lolz', 'foo': 'kitty'}这比使用更为安全eval。正如其自己的文档所说:
>>>帮助(ast.literal_eval)帮助ast模块中的literal_eval函数:literal_eval(node_or_string) 安全地评估表达式节点或包含Python的字符串 表达。提供的字符串或节点只能由以下内容组成 Python文字结构:字符串,数字,元组,列表,字典,布尔值, 和没有。
例如:
>>> eval("shutil.rmtree('mongo')")Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree onerror(os.listdir, path, sys.exc_info()) File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree names = os.listdir(path)OSError: [Errno 2] No such file or directory: 'mongo'>>> ast.literal_eval("shutil.rmtree('mongo')")Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval return _convert(node_or_string) File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert raise ValueError('malformed string')ValueError: malformed string


