gpt4 book ai didi

python - 读取引用的环境变量新行

转载 作者:行者123 更新时间:2023-12-01 02:14:06 25 4
gpt4 key购买 nike

我需要读取一个环境变量,导出时必须用引号引起来

export ENV_QUOTES="cat\nhat" # This is actually a rsa private key
export ENV_NO_QUOTES=cat\nhat

当我读入引用的环境变量时,它没有注册转义换行符:

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 识别引用的环境变量的换行符?实际输出 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

最佳答案

如果您无法更改分配输入以正确包含换行符的 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'
ENV_QUOTES=$(printf %b "$orig_shell_var") # evaluated as format string, now has newline
export ENV_QUOTES

...或者...

# in any POSIX shell
ENV_QUOTES='cat
hat'

关于python - 读取引用的环境变量新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com