[英]Make python configobj to not put a space before and after the '='
Simple question. 简单的问题。 It is possible to make configobj to not put a space before and after the '=' in a configuration entry ? 是否可以使configobj在配置条目中的'='之前和之后不留空格?
I'm using configobj to read and write a file that is later processed by a bash script, so putting an antry like: 我正在使用configobj读取和写入一个文件,该文件随后由bash脚本处理,因此放置一个如下的antry:
VARIABLE = "value" VARIABLE =“值”
breaks the bash script, it needs to always be: 破坏bash脚本,它必须始终是:
VARIABLE="value" VARIABLE = “值”
Or if someone has another suggestion about how to read and write a file with this kind of entries (and restrictions) is fine too. 或者,如果有人对如何使用此类条目(和限制)读写文件有其他建议,也可以。
Thanks 谢谢
I was looking into same and modified configobj.py by changing line 1980 in: 我正在通过更改1980行来调查相同和修改的configobj.py :
def _write_line(self, indent_string, entry, this_entry, comment)
from: 从:
self._a_to_u(' = ')
to: 至:
self._a_to_u('=')
After the change the output is without the space before and after equal sign. 更改后,输出的等号前后没有空格。
Configobj is for reading and writing ini-style config files. Configobj用于读取和写入ini样式的配置文件。 You are apparently trying to use it to write bash scripts. 您显然正在尝试使用它编写bash脚本。 That's not something that is likely to work. 那是行不通的。
Just write the bash-script like you want it to be, perhaps using a template or something instead. 只需按照自己的意愿编写bash脚本即可,也许使用模板或其他方式。
To make ConfigParses not write the spaces around the =
probably requires that you subclass it. 为了使ConfigParses不在=
周围写空格,可能需要将其子类化。 I would guess that you have to modify the write method, but only reading the code can help there. 我猜想您必须修改write方法,但是只有阅读代码才能有所帮助。 :-) :-)
Well, as suggested, I ended up writing my own parser for this that can be used exactly in the same way as ConfigObj: 好了,正如建议的那样,我最终为此编写了自己的解析器,可以与ConfigObj完全相同地使用它:
config = MyConfigParser("configuration_file")
print config["CONFIG_OPTION_1"]
config["CONFIG_OPTION_1"]= "Value 1"
print config["CONFIG_OPTION_1
config.write()
This is the code if someone is interested or wants to give suggestions (I started coding in python not so long ago so probably there are lots of room for improvement). 如果有人感兴趣或想提出建议,这就是代码(我不久前开始使用python进行编码,因此可能还有很多改进的空间)。 It respects the comments and the order of the options in the file, and correctly scapes and adds double quotes where needed: 它尊重注释和文件中选项的顺序,并正确地进行转义,并在需要时添加双引号:
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
As suggested above, it is possible to remove the spaces either side of the equals sign by making a small change to the _write_line method. 如上所述,可以通过对_write_line方法进行少量更改来删除等号两侧的空格。 This can be done conveniently by subclassing ConfigObj and overwriting _write_line as follows - 可以通过子类化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))
Then just use MyConfigObj in place of ConfigObj and all the functionality of ConfigObj is maintained 然后只需使用MyConfigObj代替ConfigObj,即可维护ConfigObj的所有功能
As Lennart suggests, configobj is probably not the right tool for the job: how about: 正如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'
since configobj returns something that looks a lot like a dict, you could probably still use it to read the data you are trying to process. 由于configobj返回的内容看起来很像字典,因此您可能仍可以使用它来读取您要处理的数据。
First of all, thanks Juancho. 首先,感谢胡安乔。 That's what i was looking for. 那就是我想要的。 But i edited the ConfigParser a little bit. 但是我稍微编辑了ConfigParser。 Now it can handle bash script arrays in form of: 现在,它可以处理以下形式的bash脚本数组:
# Network interfaces to be configured
ifaces=( "eth0" "eth1" "eth2" "eth3" )
If you set a value it just proves if an value is a list and if, it sets the quotes correctly. 如果设置了一个值,它只会证明一个值是否为列表,如果是,它将正确设置引号。 So you can set values still the same way, even it is a list: 因此,即使是列表,您也可以以相同的方式设置值:
ifaces = ['eth0', 'eth1', 'eth2', 'eth3']
conf['ifaces'] = ifaces
Here's the code: 这是代码:
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.