假设在我的环境变量中有一个关键字,其值如下
search_env_keyword_mytest=test1234
在unixshell中,如果我运行以下命令
search_env="search_env_keyword_"
find_match=`printenv | grep ${search_env}* `
then
echo $find_match will be search_env_keyword_mytest=test1234
如何在python中实现相同的效果 这是我做的,但它不起作用
pattern = "search_env_keyword_\\w+"
myPattern = re.compile(r'{linehead}'.format(linehead=pattern))
for a in os.environ:
match = re.findall(myPattern, a)
它不起作用,只是打印search_env_keyword_
而不是search_env_keyword_mytest=test1234
,我怎样才能用python打印search_env_keyword_mytest=test1234
有趣的是,您的代码示例不包含print语句,但“printing”是bug;)
在您提供的代码中,您的问题是
在python中,迭代字典是一个键列表。所以如果你的环境是 MYVAR=3 其他变量=42
您的列表将是['MYVAR','OTHERVAR']
如果你想得到你能做的一切
另外,
re
对这一点也有好处,但您可能只需要^{} 只返回字符串中匹配的部分,而不是整个字符串。(这相当于}
grep -o
。)因为每个环境变量只需匹配一次正则表达式,所以只需使用^{另外,
os.environ
是一个字典,所以a
只是键。如果还想打印该值,则需要手动添加该值相关问题 更多 >
编程相关推荐