2012-12-28 25 views
1

簡單的問題。可以讓configobj在配置條目中的'='之前和之後不放置空格。使python configobj在'='前後不放置空格

我使用configobj讀寫稍後由bash腳本處理的文件,因此把antry像:

變量爲「值」

斷bash腳本,它需要永遠是:

變量爲「值」

或者,如果有人有關於如何讀寫用這種條目(和限制)的文件中的另一個建議是沒關係。

謝謝

回答

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 
1

Configobj用於讀取和寫入ini樣式的配置文件。你顯然試圖用它來編寫bash腳本。這不太可能奏效。

只需編寫你想要的bash腳本,或許使用模板或其他東西。

爲了ConfigParses不寫=周圍的空間可能需要你繼承它。我猜你必須修改寫入方法,但只有讀取代碼才能在那裏幫助。 :-)

+1

嗯,我沒有用它來寫一個bash腳本,只寫一個包含key = value對的文件,並且它會被bash腳本讀取,兩個不同的東西。 configobj是爲此,我唯一的問題是它如何回寫文件,更改key = value的所有key = value對,從而在用值讀取文件時打破了bash腳本。 – Juancho

+0

@Juancho:呃...它是如何被bash腳本讀取的? – SingleNegationElimination

+0

@Juancho:好的。你仍然可能不能使用ConfigParser。可能你可以繼承它。 –

0

由於倫納特表明,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返回的東西,看起來很像一個字典,你很可能仍然使用它到閱讀您正在嘗試處理的數據。

+0

是的,但這種方法的問題是,該文件還包含我必須尊重的評論(以#開頭)。如果我用configobj將文件內容讀入一個字典,然後像你建議的那樣寫回來,我會放棄文件中的註釋。 這將工作,如果我只能取代改變的值,而不是寫完整的文件,因此尊重的評論或其他值沒有改變的python程序。 – Juancho

0

首先,感謝Juancho。這就是我一直在尋找的。但是我編輯了一下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 
2

我一直在尋找到同和修改configobj。PY通過改變線1980在:從

def _write_line(self, indent_string, entry, this_entry, comment) 

self._a_to_u(' = ') 

到:

self._a_to_u('=') 

改變的輸出是沒有前和等號後的空間之後。