我手头有一个非常棘手的情况(按照我的标准)。我有一个脚本需要从ConfigParser读取脚本变量名。例如,我需要阅读
self.post.id
来自 .cfg 文件并将其用作脚本中的变量。我如何实现这一目标?
我想我的查询不清楚。.cfg 文件类似于:
[head]
test: me
some variable : self.post.id
这个 self.post.id 将在运行时被替换,从脚本中获取值。
我手头有一个非常棘手的情况(按照我的标准)。我有一个脚本需要从ConfigParser读取脚本变量名。例如,我需要阅读
self.post.id
来自 .cfg 文件并将其用作脚本中的变量。我如何实现这一目标?
我想我的查询不清楚。.cfg 文件类似于:
[head]
test: me
some variable : self.post.id
这个 self.post.id 将在运行时被替换,从脚本中获取值。
测试.ini:
[head]
var: self.post.id
Python:
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 程序更简单、更清晰。