擅长:python、mysql、java
<p>[编辑]</p>
<p>现代ConfigParser支持内联注释。</p>
<pre><code>settings_cfg = configparser.ConfigParser(inline_comment_prefixes="#")
</code></pre>
<p>但是,如果您想为支持的方法浪费函数声明,这里是我的原始文章:</p>
<hr/>
<p>[原件]</p>
<p>正如SpliFF所说,文档中说,行内注释是一个no-no。第一个冒号或等号右边的所有内容都作为值传递,包括注释分隔符。</p>
<p>真糟糕。</p>
<p>所以,让我们修正一下:</p>
<pre><code>def removeInlineComments(cfgparser):
for section in cfgparser.sections():
for item in cfgparser.items(section):
cfgparser.set(section, item[0], item[1].split("#")[0].strip())
</code></pre>
<p>上面的函数遍历configParser对象的每个部分中的每个项,拆分任何“#”符号上的字符串,然后从剩余值的前边或后边去掉()的任何空白,然后只写回该值,不包含内联注释。</p>
<p>下面是这个函数的pythonic(如果可以说不那么清晰)列表理解版本,它允许您指定要拆分的字符:</p>
<pre><code>def removeInlineComments(cfgparser, delimiter):
for section in cfgparser.sections():
[cfgparser.set(section, item[0], item[1].split(delimiter)[0].strip()) for item in cfgparser.items(section)]
</code></pre>