views:

386

answers:

2

Hi, I have a very tricky situation (for my standards) in hand. I have a script that needs to read script variable name from configparser. e.g. I need to read

self.post.id

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

--Thanks Mohit

EDIT - 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 –

+3  A: 

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
Owen
So what happens when "var" in the config file is "import shutil; shutil.rmtree('/home/user')"
Jeremy Cantrell
then we have a problem!
Owen
+1  A: 

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.

S.Lott
It is in the configuration file, because the fields are CONFIGURABLE!
Mohit Ranka
@Mohit Ranka: Actually, no. It's in the source AND the source itself is configurable. Much simpler that way.
S.Lott