简体   繁体   中英

Python ConfigParser with colon in the key

How do I put a semicolon in a value in python configparser?

Python - 2.7

I have a python config parser with a section where the Key is a url and the value is a token. The key being a url contains :, -, ? and various other chars same applies to value. As you can see from the above question the special chars in the value section seems to be fine but the key does not appear to be fine.

Is there anything I can do about this? My alternatives are resolving to a json file and manually writing/reading it manually.

For example if you run the below program once I get

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

the file looks like below

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

And I get exceptions ConfigParser.NoOptionError: No option 'http://myhost.com:9090' in section: 'section'

ConfigParser on Python 2.7 is hard-coded to recognize both the colon and the equals sign as delimiters between keys and values. The current Python 3 configparser module allows you to customize the delimiters. A backport for Python 2.6-2.7 is available at https://pypi.python.org/pypi/configparser

  1. Split out your URL protocol, base and the port, ie the bits after the : and use them as a secondary keys OR
  2. Replace : with something allowed and vice-versa, possibly using a 0xnn notation or something similar OR
  3. You could use a value based on the URL such as a MD5 of the URL value as your key.

I solved a similar problem by changing the regular expression used by ConfigParser to only use = as separator.

This has been tested on Python 2.7.5 and 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>.*)$'                   
        )

see http://bugs.python.org/issue16374

semicolons are inline comment delimiters in 2.7

You can use following solution to perform your task

Replace all colons with specific special characters such as "_" or "-", which are allowed in ConfigParser

Code:

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

Output:

user:id:token

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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