来自ConfigParser的替换
-
08-07-2019 - |
题
我手头有一个非常棘手的情况(按照我的标准)。我有一个脚本需要从 ConfigParser 中读取脚本变量名称。例如,我需要阅读
self.post.id
从.cfg文件并将其用作脚本中的变量。我如何实现这一目标?
我想我的查询中不清楚。 .cfg文件类似于:
[head]
test: me
some variable : self.post.id
此self.post.id将在运行时被替换,从脚本中获取值。
解决方案
test.ini:
[head]
var: self.post.id
蟒:
import ConfigParser
class Test:
def __init__(self):
self.post = TestPost(5)
def getPost(self):
config = ConfigParser.ConfigParser()
config.read('/path/to/test.ini')
newvar = config.get('head', 'var')
print eval(newvar)
class TestPost:
def __init__(self, id):
self.id = id
test = Test()
test.getPost() # prints 5
其他提示
这有点傻。
您有一种动态语言,以源格式分发。
你正试图做出相当于源的变化。这是易于阅读的纯文本Python。
为什么不改变Python源代码并停止使用配置文件呢?
拥有像这样的代码块
要容易得多# Change this for some reason or another
x = self.post.id # Standard Configuration
# x = self.post.somethingElse # Another Configuration
# x = self.post.yetAnotherCase # A third configuration
更改配置文件与修改配置文件一样复杂。而且你的Python程序更简单,更清晰。
不隶属于 StackOverflow