Python:如何忽略#以使该行不是注释?

时间:2013-02-27 22:36:48

标签: python comments config

我在使用配置文件时遇到问题,因为该选项以#开头,因此python将其视为注释(就像它应该的那样)。

配置文件中无法正常工作的部分:

[channels]
#channel

正如您所看到的,它是一个IRC频道,这就是它需要#的原因。现在我可以使用一些丑陋的方法在我需要的时候添加#,但我更喜欢保持干净。

那么有什么办法可以忽略这个吗?因此,当我打印选项时,它将以

开头

4 个答案:

答案 0 :(得分:2)

如果您在python文件中的设置可以转义#with \

否则我认为应该在配置文件中,其他语法不会将#视为注释行

答案 1 :(得分:1)

你可能正在使用ConfigParser - 你应该提到btw - 然后你必须预先/后处理配置文件,然后将它提供给解析器,因为ConfigParser忽略了注释部分。

我可以想到两种方式,它们都使用readfp,而不是ConfigParser类的read方法: 1)从编解码器模块子类化StreamWriter和StreamReader,并使用它们将开放过程包装在透明的重新编码中。 2)使用StringIO模块中的io,如:

from io import StringIO
...
s = configfile.read()
s.replace("#","_")
f = StringIO(unicode(s))
configparser.readfp(f)

如果您不必使用" ini" -file语法,请查看json模块。我经常使用ini文件进行配置,特别是如果配置文件不应由简单用户手动编辑。

my_config={
  "channels":["#mychannel", "#yourchannel"],
  "user"="bob",
  "buddy-list":["alice","eve"],
  }

import json
with open(configfile, 'rw') as cfg:
  cfg.write(json.dumps(my_config))

答案 2 :(得分:0)

ConfigParser无法忽略以“#”开头的行。

ConfigParser.py,第476行:

        # comment or blank line?
        if line.strip() == '' or line[0] in '#;':
            continue

无法将其关闭。

答案 3 :(得分:0)

在你的辩护中,ConfigParser会让你犯这个错误:

import sys
import ConfigParser

config = ConfigParser.RawConfigParser()
config.add_section('channels')
config.set('channels', '#channel', 'true')

config.write(sys.stdout)

生成此输出:

[channels]
#channel = true

但是,您可以提供以#开头的部分名称,如下所示:

import sys
import ConfigParser

config = ConfigParser.RawConfigParser()
config.add_section('#channels')
config.set('#channels', 'channel', 'true')

config.write(sys.stdout)

with open('q15123871.cfg', 'wb') as configfile:
    config.write(configfile)

config = ConfigParser.RawConfigParser()
config.read('q15123871.cfg')
print config.get('#channels', 'channel')

产生输出:

[#channels]
channel = true

true