Python ConfigParser with colon in key
How to put semicolon in value in python configurator?
Python - 2.7
I have a python parser with a section where the key is the url and the value is the token. A key that is a URL contains :, - ,? and various other symbols also refer to value. As you can see from the above question, the special characters in the value section look ok, but the key doesn't look ok.
Is there anything I can do about this? My alternatives allow json file and manually write / read it manually.
For example, if you run the program below as soon as I receive
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 am getting exceptions ConfigParser.NoOptionError: No option 'http://myhost.com:9090' in section: 'section'
source to share
ConfigParser
on Python 2.7 is hardcoded to recognize both colon and equal sign as separators between keys and values. The current Python 3 module ConfigParser
allows custom separators. A backport for Python 2.6-2.7 is available at https://pypi.python.org/pypi/configparser
source to share
I solved a similar problem by changing the regex used ConfigParser
to be used =
as separator.
This has been tested in 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>.*)$'
)
source to share
You can use the following solution to accomplish your task
Replace all colons with special 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
source to share