简体   繁体   English

使用os.getenv时Python去除引号

[英]Python strips quotation marks when using os.getenv

I'm having difficulty with different string arrays. 我在使用不同的字符串数组时遇到困难。 Previously, there were string arrays only in properties files. 以前,仅在属性文件中存在字符串数组。 Currently, the system has string arrays in properties files and set as environmental variables in the user's .bashrc file. 当前,系统在属性文件中具有字符串数组,并在用户的.bashrc文件中将其设置为环境变量。 The string arrays look like the following in both the properties and .bashrc files. 在属性和.bashrc文件中,字符串数组都类似于以下内容。

STRING_ARRAY="host1","host2","host3"

Previously, there was a simple pair of for loops that read a series of these string arrays and passed them into some function. 以前,有一对简单的for循环,它们读取一系列这些字符串数组并将它们传递给某些函数。

for k in ("STRING_ARRAY","SOME_OTHER_ARRAY"):
   globals()[k] = globals()[k].replace("\"",'').split(",")

for stringarray,otherarray in zip(STRING_ARRAY, SOME_OTHER_ARRAY):
   someFunction(stringarray,otherarray)

This worked fine. 这很好。 The problem arose when some of the variables were moved out of properties files that were passed into the python script and into environmental variables. 当某些变量从传递到python脚本和环境变量的属性文件中移出时,出现了问题。 It seems that when using either os.getenv("HOSTSTRINGARRAY") or os.environ["HOSTSTRINGARRAY"], the os library returns the array of strings without the accompanying quotation marks so 似乎在使用os.getenv(“ HOSTSTRINGARRAY”)或os.environ [“ HOSTSTRINGARRAY”]时,os库返回的字符串数组不带引号,因此

PROPERTIES_STRING_ARRAY="host1","host2","host3"
print PROPERTIES_STRING_ARRAY

returns 退货

"host1","host2","host3"

whereas

ENV_VAR_STRING_ARRAY="host1","host2","host3"
print os.getenv("ENV_VAR_STRING_ARRAY")

returns 退货

host1,host2,host3

This is a problem because I can't seem to mix and match the two types of variables as follows 这是一个问题,因为我似乎无法如下混合和匹配两种类型的变量

for k in ("POPERTIES_STRING_ARRAY",os.getenv("ENV_VAR_OTHER_ARRAY")):
   globals()[k] = globals()[k].replace("\"",'').split(",")

for stringarray,otherarray in zip(STRING_ARRAY, os.getenv("ENV_VAR_OTHER_ARRAY")):
   someFunction(stringarray,otherarray)

So my question is, how do get os.getenv or os.environ to return a comma separated list of strings without stripping off the quotations marks enclosing the individual strings? 所以我的问题是,如何使os.getenv或os.environ返回以逗号分隔的字符串列表,而又不去除引号引起来的单个字符串?

Use ' single quote to declare the string. 使用'单引号声明字符串。 It should work now. 现在应该可以工作了。

ENV_VAR_STRING_ARRAY='"host1","host2","host3"'

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

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