按名称从模块中检索值?

时间:2015-03-13 18:13:46

标签: python python-2.7 module

我正在尝试从另一个目录中的单独.py文件中读取以下数据,特别是:“assets.ovs.screen0”。

这里显示的是assets.ovs.screen0.placement的内容:

selection_Size = [600,110]
selection_Loc  = [1500-600,208]
selection_Mov  = [0,115]

在树的底部是一个文件test.py,目前正在阅读:

import assets.ovs.screen0.placement as placement

requiredVar = "select_"

print placement.select_Size
print eval("placement."+ requiredVar)

假设有更安全/更简单的方法,那会是什么?

1 个答案:

答案 0 :(得分:2)

我可以尝试这种方式:

param = ["selection_Size", "selection_Loc", "selection_Mov", "error"]
for par in param:
    print par, placement.__dict__.get(par, None)

    # this should work too
    # print par, getattr(placement, par, None)

输出:

selection_Size [600, 110]
selection_Loc [900, 208]
selection_Mov [0, 115]
error None
相关问题