繁体   English   中英

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

[英]Make python configobj to not put a space before and after the '='

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

我正在使用configobj读取和写入一个文件,该文件随后由bash脚本处理,因此放置一个如下的antry:

VARIABLE =“值”

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

VARIABLE = “值”

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

谢谢

我正在通过更改1980行来调查相同和修改的configobj.py

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

从:

self._a_to_u(' = ')

至:

self._a_to_u('=')

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

Configobj用于读取和写入ini样式的配置文件。 您显然正在尝试使用它编写bash脚本。 那是行不通的。

只需按照自己的意愿编写bash脚本即可,也许使用模板或其他方式。

为了使ConfigParses不在=周围写空格,可能需要将其子类化。 我猜想您必须修改write方法,但是只有阅读代码才能有所帮助。 :-)

好了,正如建议的那样,我最终为此编写了自己的解析器,可以与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

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

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))

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

正如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返回的内容看起来很像字典,因此您可能仍可以使用它来读取您要处理的数据。

首先,感谢胡安乔。 那就是我想要的。 但是我稍微编辑了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM