繁体   English   中英

关键字中带有冒号的Python ConfigParser

[英]Python ConfigParser with colon in the key

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

Python-2.7

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

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

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

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")

该文件如下所示

[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的反向端口

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

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

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

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>.*)$'                   
        )

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

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

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

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

码:

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("_",":")

输出:

用户:ID:令牌

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM