键中带有冒号的 Python ConfigParser [英] Python ConfigParser with colon in the key

查看:51
本文介绍了键中带有冒号的 Python ConfigParser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何放置python configparser中值中的分号?

Python - 2.7

Python - 2.7

我有一个 python 配置解析器,其中有一个部分,其中 Key 是一个 url,值是一个令牌.关键是一个 url 包含 :, -, ?和其他各种字符同样适用于值.从上面的问题中可以看出,值部分中的特殊字符似乎没问题,但键似乎没问题.

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.

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

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

文件如下图

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

我得到异常 ConfigParser.NoOptionError: No option 'http://myhost.com:9090' in section: 'section'

推荐答案

ConfigParser 在 Python 2.7 上进行了硬编码,以将冒号和等号识别为键和值之间的分隔符.当前的 Python 3 configparser 模块允许您自定义分隔符.https://pypi.python.org/pypi/configparser

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

这篇关于键中带有冒号的 Python ConfigParser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆