python中的变量的ast.literal_eval? [英] ast.literal_eval for variables in python?

查看:373
本文介绍了python中的变量的ast.literal_eval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件 example.py
import example

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()

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

我收到错误提高ValueError('malformed string'); ValueError:格式错误的字符串

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆