簡體   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