带有冒号的Python ConfigParser

Python ConfigParser with colon in the key

如何在python configparser中的值中添加分号?

Python-2.7

我有一个带有部分的python配置解析器,其中Key是url,值是令牌。 网址关键字为:,-,?? 其他各种字符也适用于价值。 从上面的问题中可以看出,值部分中的特殊字符似乎很好,但是键似乎没有问题。

有什么我可以做的吗? 我的替代方法是解析为json文件并手动写入/手动读取。

例如,如果您运行以下程序,

1
2
3
4
5
6
7
8
9
10
11
cp = ConfigParser.ConfigParser()
cp.add_section("section")
cp.set("section","http://myhost.com:9090","user:id:token")
cp.set("section","key2","value2")
with open(os.path.expanduser("~/test.ini"),"w") as f:
    cp.write(f)

cp = ConfigParser.ConfigParser()
cp.read(os.path.expanduser("~/test.ini"))
print cp.get("section","key2")
print cp.get("section","http://myhost.com:9090")

该文件如下所示

1
2
3
[section]
http://myhost.com:9090 = user:id:token
key2 = value2

我得到异常ConfigParser.NoOptionError: No option 'http://myhost.com:9090' in section: 'section'


Python 2.7上的ConfigParser进行了硬编码,以将冒号和等号识别为键和值之间的分隔符。当前的Python 3 ConfigParser模块允许您自定义分隔符。 https://pypi.python.org/pypi/configparser提供了Python 2.6-2.7的反向端口


我通过将ConfigParser所使用的正则表达式更改为仅将=用作分隔符来解决了类似的问题。

已经在Python 2.7.5和3.4.3上进行了测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import re
try:
    # Python3
    import configparser
except:
    import ConfigParser as configparser

class MyConfigParser(configparser.ConfigParser):
   """Modified ConfigParser that allow ':' in keys and only '=' as separator.
   """

    OPTCRE = re.compile(
        r'(?P<option>[^=\\s][^=]*)'          # allow only =
        r'\\s*(?P<vi>[=])\\s*'                # for option separator          
        r'(?P<value>.*)$'                  
        )

  • 拆分您的URL协议,基本和端口,即:之后的位,并将它们用作辅助键,或
  • 替换:允许的内容,反之亦然,可能使用0xnn表示法或类似的内容,或
  • 您可以使用基于URL的值(例如URL值的MD5)作为密钥。

  • 您可以使用以下解决方案执行任务

    将所有冒号替换为ConfigParser中允许的特定特殊字符,例如" _"或"-"

    码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    from ConfigParser import SafeConfigParser

    cp = SafeConfigParser()
    cp.add_section("Install")
    cp.set("Install","http_//myhost.com_9090","user_id_token")
    with open("./config.ini","w") as f:
        cp.write(f)

    cp = SafeConfigParser()
    cp.read("./config.ini")
    a = cp.get("Install","http_//myhost.com_9090")
    print a.replace("_",":")

    输出:

    user:id:token


    参见http://bugs.python.org/issue16374

    分号是2.7中的内联注释定界符