質問

私には非常に難しい状況があります(私の基準では)。 ConfigParser からスクリプト変数名を読み取る必要があるスクリプトがあります。たとえば、読む必要があります

self.post.id
.cfgファイルから

を作成し、スクリプト内の変数として使用します。これを達成するにはどうすればよいですか

クエリが不明確だったと思います。 .cfgファイルは次のようになります。

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

このself.post.idは、スクリプトから値を取得して、実行時に置き換えられます。

役に立ちましたか?

解決

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

他のヒント

これは少しばかげています。

ソース形式で配布される動的言語があります。

ソースに変更を加えることを試みています。読みやすいプレーンテキスト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プログラムはよりシンプルで明確です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top