在 Python 命令输出上使用 grep 到 shell 脚本

Using grep on a Python command output into a shell script

过去两个小时我一直在为这个简单的例子苦苦挣扎:

我有这一行:

python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)'

给出:

Loaded plugins: product-id
{'arch': 'ia32e',
 'basearch': 'x86_64',
 'releasever': '7Server',
 'uuid': 'd68993fd-059a-4753-a7ab-1c4a601d206f',
 'yum8': 'rhel',
 'yum9': '7.1'}

现在,我只想获取带有 'releasever' 的行。

直接上我的Linux,没有问题:

$ python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)' | grep releasever
 'releasever': '7Server',

我找到了我要找的答案。

但是要放到脚本里,我好无奈。

目前,我有:

#!/bin/ksh
check="$(python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)')"


echo "${check}"
# The echo works as expected. But now, I would like to do a grep on that variable:

check2=${check}|grep releasever

echo "${check2}"

结果是空的。

我尝试了很多不同的东西,比如方括号、圆括号、引号、双引号、一体化命令,但我无法得到我想要的。 我不知道那段代码背后发生了什么,这很简单。但还是……

有人可以帮助我吗?

您的问题是您没有将 check 放入任何类型的标准输入中。这会很好用:

check2=$(echo "$check" | grep releasever)

或者您可以将 check 内容放入文件中并执行 grep <string> < <file>.

似乎有 3 个选项。

看起来 yb.conf.yumvar 是一本字典。在这种情况下,您可以在 python 脚本中打印 yb.conf.yumvar['releasever'] 目录,这样就不需要 grep 了。

其次,不要使用grep。相反,让您的 python 脚本将 yb.conf.yumvar 解析为 json 并打印它,然后从外部使用 jq 打印 releasever[=17 的值=]

第三,这是最明智的方法,直接在Python中做你想做的。 ksh 脚本在较长时间内将更难管理,因此只需在 Python 和我们 os.system 中执行您想要执行的操作即可执行外部程序。