使python configobj不在'='之前和之后放置空格

时间:2012-12-28 19:40:04

标签: python configobj

简单的问题。可以使configobj在配置条目中不在'='之前和之后放置空格吗?

我正在使用configobj来读取和写入一个稍后由bash脚本处理的文件,所以请设置一个像:

VARIABLE =“value”

打破bash脚本,它必须始终是:

VARIABLE = “值”

或者,如果某人有关于如何使用此类条目(和限制)读取和写入文件的其他建议也很好。

由于

6 个答案:

答案 0 :(得分:2)

我正在研究相同并修改 configobj.py ,改变1980年代的行:

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

从:

self._a_to_u(' = ')

为:

self._a_to_u('=')

更改后,输出在等号前后没有空格。

答案 1 :(得分:1)

Configobj用于读写ini风格的配置文件。您显然正在尝试使用它来编写bash脚本。这不是可能有用的东西。

只需按照您的意愿编写bash脚本,或者使用模板或其他内容。

要使ConfigParses不写=周围的空格,可能需要将其子类化。我猜你必须修改write方法,但只读代码可以帮助你。 : - )

答案 2 :(得分: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中编码,所以可能还有很大的改进空间)。它尊重文件中的注释和选项的顺序,并正确地scapes并在需要时添加双引号:

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

答案 3 :(得分: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的东西,你可能仍然可以用它来读取你想要处理的数据。

答案 4 :(得分: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

答案 5 :(得分:0)

如上所述,可以通过对_write_line方法进行少量更改来删除等号两侧的空格。可以通过子类化ConfigObj并按如下方式覆盖_write_line来方便地完成此操作-

develop

然后只需使用MyConfigObj代替ConfigObj,即可维护ConfigObj的所有功能