繁体   English   中英

Python 在变量中自动转义反斜杠

[英]Python is auto-escaping backslashes in variables


我目前正在尝试调试 Python 3 在变量中保留 escaping 反斜杠的问题。

情况
我有一个 Kubernetes Secret 配置,我可以在我的基于 debian 的容器中使用env | grep SECRET将其视为名为SECRET的 env 变量。 env | grep SECRET Secret 包含一个密码,该密码由字母字符和多个单反斜杠 *例如"h\ell\o"组成。 我现在想在我的 python 代码中使用这个秘密。 我想从环境变量中读取它,所以我不必在我的代码中以纯文本形式编写它。
我使用secret=os.getenv("SECRET")来引用 env 变量并初始化包含秘密的变量。 Using the python interactive shell calling secret directly shows, that it contains "h\\ell\\o" because Python is automatically escaping the backslashes. 调用print(secret)返回“h\ell\o”,因为print将双反斜杠解释为转义的反斜杠。
我现在不能使用变量SECRET来插入密码,因为它总是插入包含双反斜杠的密码,这是错误的密码。
显示所描述情况的图像

问题
有没有办法禁用自动 escaping,或替换转义的反斜杠? 我尝试了几种使用codecs.encode() or codecs.decode()的方法。 我也尝试使用string.replace()
我无法更改密码。

您可以使用repr()来获取字符串的确切表示。

您的用例示例可能如下所示:

>>> secret = "h\\ell\\o"
>>> print(secret)
h\ell\o
>>> print(repr(secret))
'h\\ell\\o'
>>> fixed_secret = repr(secret).replace("'", "") # Remove added ' ' before and after your secret since ' ' only represent the string's quotes
>>> print(fixed_secret)
h\\ell\\o
>>>
>>> # Just to make sure that both, secret and fixed_secret, are of type string
>>> type(secret)
<class 'str'>
>>> type(fixed_secret)
<class 'str'>
>>>

暂无
暂无

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

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