2013-07-30 34 views
1

How do I put a semicolon in a value in python configparser?的Python ConfigParser与结肠癌的关键

的Python - 2.7

我有一个部分,其中的关键是URL和值是一个令牌的蟒蛇配置解析器。关键是一个url包含:, - ,?和其他各种字符同样适用于价值。从上面的问题可以看出,value部分中的特殊字符似乎没有问题,但关键看起来并不好。

我能做些什么吗?我的选择是解决一个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'

回答

1
  1. 分割出你的URL协议,基地和港口,即位后:并使用它们作为第二键O [R
  2. 替换:与允许的东西,反之亦然,可能使用0xnn符号或类似的东西OR
  3. 你可以使用基于URL的值,如URL值作为你的密钥的MD5。
3

ConfigParser Python 2.7是硬编码,可识别冒号和等号作为键和值之间的分隔符。当前的Python 3 configparser模块允许您自定义分隔符。一种用于Python的反向移植2.6-2.7可在https://pypi.python.org/pypi/configparser

0

您可以使用下面的解决方案来执行你的任务

具体替换所有冒号特殊字符,如“_”或“ - ”,允许在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:令牌

1

我通过改变用于通过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>.*)$'     
     )