0

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

self.post.id

.cfg ファイルから取得し、スクリプトで変数として使用します。どうすればこれを達成できますか?

私は私の質問で不明確だったと思います。.cfg ファイルは次のようになります。

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

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

4

2 に答える 2

5

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
于 2008-11-17T07:02:53.820 に答える
0

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

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

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

于 2008-11-17T14:53:43.857 に答える