Inplace substitution from ConfigParser

断了今生、忘了曾经 提交于 2019-12-24 20:52:28

问题


I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read

self.post.id

from a .cfg file and use it as a variable in the script. How do I achieve this?

I suppose I was unclear in my query. The .cfg file looks something like:

[head]
test: me
some variable : self.post.id

This self.post.id is to be replaced at the run time, taking values from the script.


回答1:


test.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



回答2:


This is a bit silly.

You have a dynamic language, distributed in source form.

You're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python.

Why not just change the Python source and stop messing about with a configuration file?

It's a lot easier to have a block of code like this

# 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

it's just as complex to change this as it is to change a configuration file. And your Python program is simpler and more clear.



来源:https://stackoverflow.com/questions/295028/inplace-substitution-from-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!