在ConfigParser Python中使用冒号 [英] Using colons in ConfigParser Python
本文介绍了在ConfigParser Python中使用冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据文档:
配置文件由
节组成,由[section] $ b,后跟名称:值条目,
,其格式为RFC
822(见第3.1.1节LONG HEADER
FIELDS)。 name = value也被接受。
Python文档
但是,编写配置文件总是使用等号(=)。是否有任何选项使用冒号(:)?
However, writing a config file always use the equal sign (=). Is there any option to use the colon sign (:)?
提前感谢。
p>
推荐答案
如果你看看定义 RawConfigParser.write
code> ConfigParser.py ,你会看到等号是硬编码的。因此,要更改行为,您可以子类化您希望使用的ConfigParser:
If you look at the code defining the RawConfigParser.write
method inside ConfigParser.py
you'll see that the equal signs are hard-coded. So to change the behavior you could subclass the ConfigParser you wish to use:
import ConfigParser
class MyConfigParser(ConfigParser.ConfigParser):
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % 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__":
fp.write("%s : %s\n" %
(key, str(value).replace('\n', '\n\t')))
fp.write("\n")
filename='/tmp/testconfig'
with open(filename,'w') as f:
parser=MyConfigParser()
parser.add_section('test')
parser.set('test','option','Spam spam spam!')
parser.set('test','more options',"Really? I can't believe it's not butter!")
parser.write(f)
产生:
[test]
more options : Really? I can't believe it's not butter!
option : Spam spam spam!
这篇关于在ConfigParser Python中使用冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文