我需要读取一个env变量,该变量必须在导出时引用
export ENV_QUOTES="cat\nhat" # This is actually a rsa private key
export ENV_NO_QUOTES=cat\nhat
当我在引用的env var中读到它时,它没有注册转义的换行符:
import os
env_var_no_quotes = os.environ['ENV_NO_QUOTES']
env_var = os.environ['ENV_QUOTES']
for idx, v in enumerate(env_var_no_quotes):
print(idx, v, env_var[idx])
输出:
0 c c
1 a a
2 t t
3 n \
4 h n
5 a h
6 t a
如何让python识别引用的env变种的换行符?私钥的实际输出print
如下所示:
# Non quoted
-----BEGIN PRIVATE KEY-----
ffaffdsafsdeeekqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCltThZlt88aAn8
f2MlQsV4Nv9TEhBj8WUypfGc148FedpTRraNyE3f9bZ4u4MJC34vI9zuqf5hNrX+
+w+eYrPJwbS4CvA3Ww2znjCfKK4u3n3P522LTGNxAoGBAK5AA0twCSifwIPIlIsZ
psGtFIEJpc6sJ4+LgVzTW/5EwreMHMnx3tQTaVi6pVIJTqjaMJp5SAAUlPrl5zZM
gsVgtwyXMMqlKNt9wMdBH+ir7oJsppC+DjIRbpCa8U6nEG4Wij5qVeRJ8DVV8NAM
C5Tc+6qgzVZRaXXkCStZA/PK
-----END PRIVATE KEY-----
# Quoted
-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCltThZlt88aAn8\nf2MlQsV4Nv9TEhBj8WUypfGc148FedpTRraNyE3f9bZ4u4MJC34vI9zuqf5hNrX+\nW+UfXJkPLfemupraI5sTWyFCwX7ZYOd5I7vyRoqSii4MHCXlg8zWySrjwirwou87\nn18zSyA30fu3kuHBDlHFnRVw+Ag+M/XjesRcz5Q+KQ9o/MnpcZcYQ7sZU5GntqCw\n3ZNgb68Cla87jbhvlkjfdN77IcLJypuwCMZeyHeQYNtgxLyE0o2Te5ddAjvD59uS\nML69iuQqpvPjpuBgZnReKX3oZusU/o6qgzVZRaXXkCStZA/PK\n-----END PRIVATE KEY-----\n
答案 0 :(得分:1)
如果您无法更改shell脚本,请将输入正确地包含换行文字(这是更好的方法!),您只需在Python中使用string.sub()
来替换r'\n'
(这是变量实际包含的内容)'\n'
(这是你想要的):
env_var = os.environ['ENV_QUOTES'].replace(r'\n', '\n')
那就是说,在shell方面,考虑一下:
# in bash or ksh, not POSIX sh
ENV_QUOTES=$'cat\nhat' # literal newline, not '\' followed by 'n'
...或...
# in any POSIX shell
orig_shell_var='cat\nhat' # two characters, '\' then 'n'
printf -v ENV_QUOTES %b "$orig_shell_var" # evaluated as format string, now has newline
export ENV_QUOTES