来自 ConfigParser 的就地替换

Moh*_*nka 0 python configuration-files

我手头有一个非常棘手的情况(就我的标准而言)。我有一个脚本需要从ConfigParser读取脚本变量名称。例如,我需要阅读

self.post.id
Run Code Online (Sandbox Code Playgroud)

从 .cfg 文件并将其用作脚本中的变量。我如何实现这一目标?

我想我的查询不清楚。.cfg 文件类似于:

[head]
test: me
some variable : self.post.id
Run Code Online (Sandbox Code Playgroud)

这个 self.post.id 将在运行时被替换,从脚本中获取值。

Owe*_*wen 5

测试.ini:

[head]
var: self.post.id
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • 那么当配置文件中的“var”为“import Shutil; Shutil.rmtree('/home/user')”时会发生什么 (2认同)