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 |
我得到异常
Python 2.7上的
我通过将
已经在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>.*)$' ) |
您可以使用以下解决方案执行任务
将所有冒号替换为
码:
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中的内联注释定界符