2013-07-30 36 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>.*)$'     
     )