如何在使用ConfigParser将其作为环境变量读取时,在Python字符串中转义字符

问题描述 投票:0回答:1

我遇到以下错误---“ configparser.InterpolationSyntaxError:'%'之后必须是'%'或'(',找到的是'%dCUD'”]

I want to read credentials which are set as an environment variables as well as present in .config file. So I am using pythons ConfigParser as follows.

import configparser as cp
from configparser import ConfigParser
config = ConfigParser(os.environ)    #<-- this enables ConfigParser to read from environment variable
config.read(CONFIG_FILEPATH)       #<--- this is to read from .confog file


My .config file is like this--
[Postgres]
Postgres.host = XXX.com
Postgres.METADATADB=pda-study-beta
Postgres.DATAREFRESHDB=
Postgres.user= %(XXXX)s
Postgres.password = %(Postgres_Pass)s

anything included inside *%()s* means it is being read from environment variable. 

I read it in my scripts as follows:
config.get('Postgres','Postgres.password')


It works fine for all but for password, its throwing me following error in password section--
"configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%dCUD'"

Its because my password contains '%' character. e.g.(xxx%dCUDxx)

Does any one have any idea how do I handle this. We can escape % with another %, but in my case, I am reading password from environment variable, so cant manipulate it. 

Can anyone please help me resolve this ?
python-3.x environment-variables configparser
1个回答
0
投票

configparser模块文档不明确,但是如果您查看源代码,则可以在方法_interpolate_some中看到%扩展是递归的。也就是说,也将%扩展为插值-您的示例中的密码。

我正在从环境变量读取密码,因此无法对其进行操作。

的确,您可能不想突变全局环境变量。但是,没有什么能阻止您制作副本和对该副本进行变异。例如,

config = ConfigParser({k: v.replace('%', '%%') for k, v in os.environ.items()})
© www.soinside.com 2019 - 2024. All rights reserved.