python中变量的ast.literal_eval? [英] ast.literal_eval for variables in python?
问题描述
假设我有一个文件 example.py
:导入示例
Suppose I have a file example.py
:
import example
VVV = 2
DictionaryNameB = {
'a' : VVV,
'bb' : 'SomethingB',
'c' : False,
'ccc' : None,
'dddd' : 'true',
'eeeee' : 0.123456,
'f' : 2,
'h' : [1,2,3]
}
我写了一个使用 ast.literal_eval()
的函数:
I wrote a function that uses ast.literal_eval()
:
def getDicFromFile(self, dic_name):
with open( 'example.py' ) as f:
file_data = f.read()
match = re.findall('%s[^{]+{[^}]+}' % dic_name, file_data, re.MULTILINE)[0]
# print(match)
dicObject = ast.literal_eval(match[len(dic_name)+3:])
return dicObject
我收到错误 raise ValueError('malformed string') ;值错误:格式错误的字符串
I got the error raise ValueError('malformed string') ; ValueError: malformed string
我知道 ast.literal_eval()
无法解码变量 VVV
,还有其他方法可以做到吗?
I understand that ast.literal_eval()
can't decode the variable VVV
, is there another way to do it?
推荐答案
你可以使用 asteval
,一个建立在 ast
解析树上以执行有限语句的库.它将开箱即用地处理您的示例:
You could use asteval
, a library that builds on the ast
parse tree to execute limited statements. It'll handle your example out of the box:
from asteval import Interpreter
aeval = Interpreter()
aeval(file_data)
dicObject = aeval.symtable['DictionaryNameB']
或者,您可以直接导入文件:
Or, you could just import the file:
from importlib import import_module
module = import_module('example')
dicObject = module.DictionaryNameB
asteval
允许使用相当多的 Python 结构.您可以将 Python 抽象语法 与 aeval.node_handlers
映射寄存器,只需删除任何不需要的.例如,您可以删除函数定义和调用、循环、二进制操作 (binop
) 和异常处理.
asteval
allows for quite a wide number of Python constructs. You could compare the Python Abstract Grammar with what handlers the aeval.node_handlers
mapping registers, and simply delete any you don't need. You could remove function definitions and calling, looping, binary operations (binop
) and exception handling, for example.
这篇关于python中变量的ast.literal_eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!