簡體   English   中英

關鍵字中帶有冒號的Python ConfigParser

[英]Python ConfigParser with colon in the key

如何在Python configparser中的值中添加分號?

Python-2.7

我有一個帶有部分的python配置解析器,其中Key是url,值是令牌。 網址關鍵字為:,-,?。 其他各種字符也適用於價值。 從上面的問題中可以看出,值部分中的特殊字符似乎很好,但是鍵似乎沒有問題。

有什么我可以做的嗎? 我的替代方法是解析為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'

Python 2.7上的ConfigParser進行了硬編碼,以將冒號和等號識別為鍵和值之間的分隔符。 當前的Python 3 configparser模塊允許您自定義分隔符。 https://pypi.python.org/pypi/configparser提供了Python 2.6-2.7的反向端口

  1. 拆分URL協議,基本和端口,即:之后的位,並將它們用作輔助鍵,
  2. 替換:允許的內容,反之亦然,可能使用0xnn表示法或類似的內容,
  3. 您可以使用基於URL的值(例如URL值的MD5)作為密鑰。

我通過將ConfigParser使用的正則表達式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>.*)$'                   
        )

參見http://bugs.python.org/issue16374

分號是2.7中的內聯注釋定界符

您可以使用以下解決方案執行任務

將所有冒號替換為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:令牌

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM