从python 2.7.3升级到2.7.9后,停止ConfigParser向delims添加空格
问题内容:
在被迫使用更高版本的python之后,ConfigParser现在坚持在修改配置文件时在所有delims的每一侧添加空格。
例如,setting = 90变为:setting = 90
这不是早期版本中的行为,我找不到控制这种行为的方法,有人可以帮忙吗?
我的测试代码如下所示:
import ConfigParser
import os
config = ConfigParser.ConfigParser()
cfgfile = '/home/osmc/bin/test/config.txt'
os.system('sudo echo "[section]" > ' + cfgfile)
os.system('sudo echo "setting=0" >> ' + cfgfile)
config.read(cfgfile)
config.set('section','setting', '1' )
with open(cfgfile, 'wb') as newcfgfile:
config.write(newcfgfile)
提前致谢。
问题答案:
您可以创建子类并更改.write方法,以从以下位置的两侧删除空格 =
:
import ConfigParser
import os
class MyConfigParser(ConfigParser.ConfigParser):
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key == "__name__":
continue
if (value is not None) or (self._optcre == self.OPTCRE):
key = "=".join((key, str(value).replace('\n', '\n\t')))
fp.write("%s\n" % key)
fp.write("\n")
config = MyConfigParser()
.....