简体   繁体   English

使用ConfigParser在配置文件中使用Python转义分隔符

[英]Python escape delimiter in configuration file using ConfigParser

I'd like to escape ":" and/or "=" as the name in a configuration file. 我想将“:”和/或“ =”转义为配置文件中的名称。 Does anyone know how to achieve this? 有谁知道如何实现这一目标? I try backslash "\\", it does not work. 我尝试反斜杠“ \\”,它不起作用。

If you're using Python 3, you don't need to. 如果您使用的是Python 3,则不需要。 Look at the Python docs section on Customizing Parser Behavior . 查看有关自定义解析器行为的Python文档部分。 By default, configparser uses ":" and "=" as delimiters, but you can specify different delimiters when you create the configparser object: 默认情况下,configparser使用“:”和“ =”作为分隔符,但是在创建configparser对象时可以指定不同的分隔符:

import configparser

parser = configparser.ConfigParser(delimiters=('?', '*'))

In this example, the default delimiters have been replaced with a question mark and an asterisk. 在此示例中,默认定界符已替换为问号和星号。 You can change the delimiters to whatever characters you want that won't conflict with the information you need to put in the config file. 您可以将定界符更改为所需的任何字符,这些字符不会与需要放入配置文件中的信息冲突。

The above listed method will only work for Python 3, as the Python 2 ConfigParser is hard-coded to recognize equal signs and colons as delimiters. 上面列出的方法仅适用于Python 3,因为Python 2 ConfigParser被硬编码为将等号和冒号识别为定界符。 According to this SO question , there is a backported configparser available for the 2.7 intepreter at https://pypi.python.org/pypi/configparser . 根据这个SO问题 ,在https://pypi.python.org/pypi/configparser有一个用于2.7解释器的反向移植的configparser。 See if that will work for you. 看看是否适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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