使用ConfigParser在配置文件中使用Python转义分隔符 [英] Python escape delimiter in configuration file using ConfigParser

查看:392
本文介绍了使用ConfigParser在配置文件中使用Python转义分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在配置文件中转义:和/或 =。
有人知道如何实现吗?
我尝试反斜杠 \,它不起作用。

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.

推荐答案

如果您使用的是Python 3,您不需要。查看自定义解析器行为上的Python文档部分。 。默认情况下,configparser使用:和 =作为分隔符,但是在创建configparser对象时可以指定不同的分隔符:

If you're using Python 3, you don't need to. Look at the Python docs section on Customizing Parser Behavior. By default, configparser uses ":" and "=" as delimiters, but you can specify different delimiters when you create the configparser object:

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.

上面列出的方法仅适用于与Python 2 ConfigParser一样,Python 3也经过硬编码,可以识别等号和冒号作为分隔符。根据此SO问题,在 https://pypi.python.org/pypi/configparser 。看看是否适合您。

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. According to this SO question, there is a backported configparser available for the 2.7 intepreter at https://pypi.python.org/pypi/configparser. See if that will work for you.

这篇关于使用ConfigParser在配置文件中使用Python转义分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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