2

簡単な質問です。構成エントリの「=」の前後にスペースを入れないように configobj を作成することは可能ですか?

configobj を使用して、後で bash スクリプトによって処理されるファイルの読み取りと書き込みを行っているため、次のような Antry を配置します。

変数 = 「値」

は bash スクリプトを壊します。常に次のようにする必要があります。

変数="値"

または、この種のエントリ (および制限) を含むファイルを読み書きする方法について別の提案があれば、それも結構です。

ありがとう

4

6 に答える 6

1

Configobjは、iniスタイルの構成ファイルを読み書きするためのものです。あなたはどうやらそれを使ってbashスクリプトを書こうとしているようです。それはうまくいく可能性が高いものではありません。

代わりにテンプレートなどを使用して、bashスクリプトを思いどおりに記述してください。

ConfigParsesの周囲にスペースを書き込まないようにするには、=おそらくサブクラス化する必要があります。writeメソッドを変更する必要があると思いますが、コードを読み取るだけで役に立ちます。:-)

于 2012-12-28T20:27:37.037 に答える
1

さて、示唆されているように、ConfigObj とまったく同じように使用できる独自のパーサーを作成することになりました。

config = MyConfigParser("configuration_file")
print config["CONFIG_OPTION_1"]  
config["CONFIG_OPTION_1"]= "Value 1"
print config["CONFIG_OPTION_1
config.write()

これは、誰かが興味を持っているか、提案をしたい場合のコードです (私はそれほど前に Python でコーディングを始めたので、おそらく改善の余地がたくさんあります)。ファイル内のコメントとオプションの順序を尊重し、必要に応じて正しくエスケープして二重引用符を追加します。

import os
import sys

class MyConfigParser:
  name = 'MyConfigParser'
  debug = False
  fileName = None
  fileContents = None
  configOptions = dict()  

  def __init__(self, fileName, debug=False):
    self.fileName = fileName
    self.debug = debug    
    self._open()

  def _open(self):       
    try:
        with open(self.fileName, 'r') as file:
    for line in file:
      #If it isn't a comment get the variable and value and put it on a dict
      if not line.startswith("#") and len(line) > 1:
    (key, val) = line.rstrip('\n').split('=')
    val = val.strip()
    val = val.strip('\"')
    val = val.strip('\'')
    self.configOptions[key.strip()] = val
except:
  print "ERROR: File "  + self.fileName + " Not Found\n"

  def write(self):
try:
  #Write the file contents
  with open(self.fileName, 'r+') as file:
    lines = file.readlines()
    #Truncate file so we don't need to close it and open it again 
    #for writing
    file.seek(0)
    file.truncate()      

    i = 0
    #Loop through the file to change with new values in dict      
    for line in lines:    
      if not line.startswith("#") and len(line) > 1:
    (key, val) = line.rstrip('\n').split('=')
    try:
      if key in line:
        newVal = self.configOptions[key]
        #Only update if the variable value has changed
        if val != newVal:
          newLine = key + "=\"" + newVal + "\"\n"
          line = newLine
    except:
      continue
      i +=1
      file.write(line)
except IOError as e:
  print "ERROR opening file " + self.fileName + ": " + e.strerror + "\n"


  #Redefinition of __getitem__ and __setitem__

  def __getitem__(self, key):  
try:
  return self.configOptions.__getitem__(key)
except KeyError as e:
  if isinstance(key,int):
    keys = self.configOptions.keys()
    return self.configOptions[keys[key]]
  else:
    raise KeyError("Key " +key+ " doesn't exist")

  def __setitem__(self,key,value):
self.configOptions[key] = value
于 2012-12-31T08:11:46.207 に答える
0

まず、フアンチョに感謝します。それが私が探していたものです。しかし、私は ConfigParser を少し編集しました。次の形式で bash スクリプト配列を処理できるようになりました。

# Network interfaces to be configured
ifaces=( "eth0" "eth1" "eth2" "eth3" )

値を設定すると、値がリストであるかどうかが証明され、その場合は引用符が正しく設定されます。したがって、リストであっても、同じ方法で値を設定できます。

ifaces = ['eth0', 'eth1', 'eth2', 'eth3']
conf['ifaces'] = ifaces

コードは次のとおりです。

import os
import sys

class MyConfigParser:
    name = 'MyConfigParser'
    debug = False
    fileName = None
    fileContents = None
    configOptions = dict()  
    qouteOptions = dict()

    def __init__(self, fileName, debug=False):
        self.fileName = fileName
        self.debug = debug    
        self._open()

    def _open(self):       
        try:
            with open(self.fileName, 'r') as file:
                for line in file:
                    #If it isn't a comment get the variable and value and put it on a dict
                    if not line.startswith("#") and len(line) > 1:
                        (key, val) = line.rstrip('\n').split('=')
                        val = val.strip()
                        val = val.strip('\"')
                        val = val.strip('\'')
                        self.configOptions[key.strip()] = val
                        if val.startswith("("):
                            self.qouteOptions[key.strip()] = ''
                        else:
                            self.qouteOptions[key.strip()] = '\"'
        except:
            print "ERROR: File "  + self.fileName + " Not Found\n"

    def write(self):
        try:
            #Write the file contents
            with open(self.fileName, 'r+') as file:
                lines = file.readlines()
                #Truncate file so we don't need to close it and open it again 
                #for writing
                file.seek(0)
                file.truncate()      

                #Loop through the file to change with new values in dict      
                for line in lines:
                    if not line.startswith("#") and len(line) > 1:
                        (key, val) = line.rstrip('\n').split('=')
                        try:
                            if key in line:
                                quotes = self.qouteOptions[key]

                                newVal = quotes +  self.configOptions[key] + quotes

                                #Only update if the variable value has changed
                                if val != newVal:
                                    newLine = key + "=" + newVal + "\n"
                                    line = newLine
                        except:
                            continue
                    file.write(line)
        except IOError as e:
                print "ERROR opening file " + self.fileName + ": " + e.strerror + "\n"


    #Redefinition of __getitem__ and __setitem__

    def __getitem__(self, key):  
        try:
            return self.configOptions.__getitem__(key)
        except KeyError as e:
            if isinstance(key,int):
                keys = self.configOptions.keys()
                return self.configOptions[keys[key]]
            else:
                raise KeyError("Key " + key + " doesn't exist")

    def __setitem__(self, key, value):
        if isinstance(value, list):
            self.qouteOptions[key] = ''
            value_list = '('
            for item in value:
                value_list += ' \"' + item + '\"'
            value_list += ' )'
            self.configOptions[key] = value_list
        else:
            self.qouteOptions[key] = '\"'
            self.configOptions[key] = value
于 2014-03-27T11:35:01.157 に答える
0

Lennart が示唆するように、configobj はおそらくこの仕事に適したツールではありません。

>>> import pipes
>>> def dict2bash(d):
...     for k, v in d.iteritems():
...         print "%s=%s" % (k, pipes.quote(v))
...         
>>> dict2bash({'foo': "bar baz quux"})
foo='bar baz quux'

configobj は dict によく似たものを返すので、おそらくそれを使用して、処理しようとしているデータを読み取ることができます。

于 2012-12-28T20:31:37.850 に答える