使python configobj在'=';

使python configobj在'=';,python,configobj,Python,Configobj,简单的问题。是否可以使configobj在配置条目中的“=”前后不放置空格 我正在使用configobj读写一个文件,该文件稍后将由bash脚本进行处理,因此使用如下命令: VARIABLE=“value” 中断bash脚本,它需要始终: VARIABLE=“value” 或者,如果有人对如何读写具有此类条目(和限制)的文件有其他建议,也可以 感谢Configobj用于读取和写入ini样式的配置文件。显然,您正试图使用它来编写bash脚本。这不太可能奏效 只需按照您希望的方式编写bash脚本,或

简单的问题。是否可以使configobj在配置条目中的“=”前后不放置空格

我正在使用configobj读写一个文件,该文件稍后将由bash脚本进行处理,因此使用如下命令:

VARIABLE=“value”

中断bash脚本,它需要始终:

VARIABLE=“value”

或者,如果有人对如何读写具有此类条目(和限制)的文件有其他建议,也可以


感谢

Configobj用于读取和写入ini样式的配置文件。显然,您正试图使用它来编写bash脚本。这不太可能奏效

只需按照您希望的方式编写bash脚本,或许可以使用模板或其他方法


要使ConfigParses不写入
=
周围的空格,可能需要对其进行子类化。我想您必须修改write方法,但只有阅读代码才能帮助您完成

正如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,因此您可能仍然可以使用它来读取您试图处理的数据。

正如所建议的,我最终为此编写了自己的解析器,其使用方式与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

首先,谢谢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

我正在研究相同的配置对象,并通过更改1980年的行修改了configobj.py

def _write_line(self, indent_string, entry, this_entry, comment)
发件人:

致:


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

如上所述,可以通过对_write _line方法进行微小更改来删除等号两侧的空格。通过将ConfigObj子类化并覆盖_write_行,可以方便地完成此操作,如下所示-

from configobj import ConfigObj

class MyConfigObj(ConfigObj):

    def __init__(self, *args, **kwargs):
        ConfigObj.__init__(self, *args, **kwargs)

    def _write_line(self, indent_string, entry, this_entry, comment):
        """Write an individual line, for the write method"""
            # NOTE: the calls to self._quote here handles non-StringType values.
        if not self.unrepr:
            val = self._decode_element(self._quote(this_entry))
        else:
            val = repr(this_entry)

        return '%s%s%s%s%s' % (indent_string,
                           self._decode_element(self._quote(entry, multiline=False)),
                           self._a_to_u('='),
                           val,
                           self._decode_element(comment))

然后用MyConfigGobj代替ConfigObj,ConfigObj的所有功能都得到了维护

我不是用它来写bash脚本,只是写一个包含key=value对的文件,它将被bash脚本读取,这是两件不同的事情。configobj就是为了这个,我唯一的问题是它如何写回文件,更改key=value的所有key=value对,从而在读取带有值的文件时破坏bash脚本。@Juancho:OK。您仍然可能无法按原样使用ConfigParser。也许你可以对它进行子类化。是的,但这种方法的问题是,该文件还包含我必须尊重的注释(以#开头)。如果我用configobj将文件内容读入dict,然后像您建议的那样写回,我将在文件中删除注释。如果我只能替换已更改的值,而不是编写完整的文件,从而尊重python程序未更改的注释或其他值,那么这将是可行的。
self._a_to_u('=')
from configobj import ConfigObj

class MyConfigObj(ConfigObj):

    def __init__(self, *args, **kwargs):
        ConfigObj.__init__(self, *args, **kwargs)

    def _write_line(self, indent_string, entry, this_entry, comment):
        """Write an individual line, for the write method"""
            # NOTE: the calls to self._quote here handles non-StringType values.
        if not self.unrepr:
            val = self._decode_element(self._quote(this_entry))
        else:
            val = repr(this_entry)

        return '%s%s%s%s%s' % (indent_string,
                           self._decode_element(self._quote(entry, multiline=False)),
                           self._a_to_u('='),
                           val,
                           self._decode_element(comment))