使用 python 语法配置文件的最佳方法是什么(当然是在 python 中)?
我的配置文件实际上只是一个大的 python 字典,但我有很多配置文件来运行不同的实验,并且我想根据命令行选项“导入”不同的文件。本能地,我想做 import ConfigFileName ,其中 ConfigFileName 是一个字符串,其中包含配置文件的 python 包名称...但这不起作用。
有什么想法吗?
My config file is really just a big python dict, but I have many config files to run different experiments and I want to 'import' a different one based on a command line option. Instinctively I want to do import ConfigFileName where ConfigFileName is a string with the config file's python package name in it... but that doesn't work.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
__import__
内置函数。但像 nosklo 一样,我更喜欢以更简单的数据格式存储它,例如 INI 配置文件的 JSON。Use the
__import__
builtin function. But like nosklo, I prefer to store it in simpler data format like JSON of INI config file.切换到 json。它包含在 python 中,并为配置文件提供了更好的整体格式。
Switch to json. It's included with python and makes a better format overall for config files.
您可能会考虑 ConfigParser,它也包含在 python 中。它提供简单的分段名称/值项、默认设置和一些替换功能。如果这足够灵活以满足您的需求,那么这将是一个不错的选择。
You might consider ConfigParser, also included with python. It offers simple sectioned name/value items, default settings, and some substitution capabilities. If that's flexible enough for your needs, it would be a nice alternative.