我不熟悉 config 模块本身,但想象你可以使用内置功能轻松地执行类似于下面所示的操作 ConfigParser (要么 configparser 在Python 3)模块中。
config
ConfigParser
configparser
鉴于此配置文件:
[Section1] x: 0.1 sin_of_x: math.sin(x)
这段代码:
import ConfigParser import math parser = ConfigParser.ConfigParser() parser.read('eval_config.cfg') namespace = {'__builtins__': None, 'math': math} for name, value in parser.items('Section1'): value = eval(value, namespace) print('{!r} = {!r}'.format(name, value)) namespace[name] = value
输出:
'x' = 0.1 'sin_of_x' = 0.09983341664682815
如果您不想硬编码模块的名称,可以单独添加 [Modules] 部分到配置文件以在使用前定义它们。
[Modules]