简单的问题。是否可以使 configobj 在配置条目中的“=”前后不放置空格?
我正在使用 configobj 来读取和写入稍后由 bash 脚本处理的文件,因此放置一个类似的antry:
变量 = “价值”
破坏 bash 脚本,它必须始终是:
变量="值"
或者,如果有人对如何使用这种条目(和限制)读写文件有其他建议也可以。
谢谢
我正在通过更改第 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 返回的东西看起来很像 dict,您可能仍然可以使用它来读取您尝试处理的数据。
首先,感谢胡安乔。这就是我一直在寻找的。但我稍微编辑了 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