简体   繁体   中英

Using grep on a Python command output into a shell script

I've been struggling for the past two hours on this simple example :

I have this line:

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

Which gives:

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

And now, I would just like to get the line with the 'releasever'.

Directly on my Linux, there is no problem:

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

I have the answer I am looking for.

But when it comes to put it in a script, I am so helpless.

Currently, I have:

#!/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}"

And the result is empty.

I've tried a lot of different things, like brackets, parentheses, quote, double quote, all-in-one command, but I can't get what I want. I don't know what's happening behind that code, which is very simple. But still…

Can someone help me?

There seem to be 3 options.

It looks like yb.conf.yumvar is a dictionary. In which case, you could either print yb.conf.yumvar['releasever'] directory in your python script in which case the grep would be unnecessary.

Secondly, don't use grep. Instead, have your python script parse the yb.conf.yumvar into json and print it and then use jq from the outside to print the value of releasever

Third, and this is the sanest way, do what you want in Python directly. ksh scripts will be harder to manage over a longer period of time so just do what you want to do in Python and us os.system to execute external programs.

Your problem is that you are not putting check in any kind of std input. This would work fine:

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

or you could put check content into a file and do like grep <string> < <file> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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