Skip to content
Advertisement

python way to find unique version of software

I’ve multiple components of a software (let’s call it XYZ) installed on my linux (RHEL 6.2) server running python 3.3.

~$ rpm -qa | grep -i xyz
XYZman-5.3.1.9-1.x86_64
XYZconnect-5.3.1.9-1.x86_64
XYZconsole-5.3.1.9-1.x86_64
XYZnode-5.3.1.9-1.x86_64

I’m trying to covert my install/upgrade script from shell to python. For that I need to fetch the version number, but only once. In my python script I’ve added the below code

>>> cmd = ("rpm -qa | grep -i xyz | awk -F[-] '{print $2}' | sort -u")
>>> sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
>>> (out, err) = sp.communicate()
>>> rcode = sp.returncode

>>> print (out.decode('utf-8').replace('n', '')
>>> 5.3.1.9

I want to use python based commands instead of awk and sort in this. I think we can use split() for awk, but couldn’t figure out the proper way for it. Can we use python sort to get unique value like sort -u in shell.

Advertisement

Answer

You can define the delimeter to use in split() method, like this:

>>> cmd = ("rpm -qa | grep -i xyz")
>>> sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
>>> (out, err) = sp.communicate()
>>> v = []
>>> for line in out.splitlines():
...     if line.split("-")[1] not in v:
...         v.append(line.split("-")[1])
...
>>> print v
['5.3.1.9']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement