如何在类似python的grep中使用通配符搜索环境变量

2024-09-25 06:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

假设在我的环境变量中有一个关键字,其值如下

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


Tags: 命令reenvsearchmatch环境变量关键字find
2条回答

有趣的是,您的代码示例不包含print语句,但“printing”是bug;)

在您提供的代码中,您的问题是

for a in os.environ:
  do_something

在python中,迭代字典是一个键列表。所以如果你的环境是 MYVAR=3 其他变量=42

您的列表将是['MYVAR','OTHERVAR']

如果你想得到你能做的一切

for key, value in os.environ.items():
  line = key + "=" + value

另外,re对这一点也有好处,但您可能只需要

if 'mysearchstring' in line:
  print(line)

^{}只返回字符串中匹配的部分,而不是整个字符串。(这相当于grep -o。)因为每个环境变量只需匹配一次正则表达式,所以只需使用^{}

另外,os.environ是一个字典,所以a只是键。如果还想打印该值,则需要手动添加该值

myPattern = re.compile(r'search_env_keyword_\w+')
for key, val in os.environ.items():
    if myPattern.match(a):
        print(f'{key}={val}')

相关问题 更多 >