0

I would like to investagate in a linux VM whether XY package is installed. The output is 1, but after if statement its not printed that XY is installed. Can you give me some idea how can I solve this problem.

import os 
import commands

status, output = commands.getstatusoutput("rpm -qa | grep XY |wc -l")
if(output==1):
    print("XY is installed on this pc")
Viktor
  • 7
  • 3
  • Does [this](https://stackoverflow.com/questions/1051254/check-if-python-package-is-installed) help? – 0x263A Jul 17 '21 at 18:12
  • Are you sure the desired result is put into `output`, and not `status`? print out both variables outside the if-statement to check. – sommervold Jul 17 '21 at 18:13
  • If you use `grep` correctly, you don't need to check its output and can go only on exit status. See in particular `grep -q`, which tells it not to output anything at all; since it doesn't need to write output, it can exit (with a successful exit status) the moment it finds a match, without needing to read remaining input. – Charles Duffy Jul 17 '21 at 19:55
  • Beyond that, `wc` will write something like the string `'1\n'`, which is certainly not equal to the integer `1`, so it's completely normal for your `if` to evaluate to false. – Charles Duffy Jul 17 '21 at 19:56

1 Answers1

1

The output from wc is a string; it can never be equal to an integer. You can convert it, or compare to '1', but this is all a useless use of wc anyway.

A better approach altogether would be to run just the rpm command as a subprocess, and check its output with a simple native Python snippet.

import subprocess

if 'XY' in subprocess.check_output(['rpm', '-qa']):
    print('XY is installed')

This is somewhat prone to false positives, because you are checking if any part of the output contains 'XY' as a substring anywhere. If you have libXY-dev or ABCXYZ installed, it will incorrectly claim that you have XY. It would probably be better to query RPM for the status of this particular package only; but hopefully this should at least get you started.

Perhaps also notice how this avoids a shell which is always a win, especially if you are not too familiar with the shell and its pitfalls.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Add a `.split('\n')` before the `in` and you'll be doing an exact string match (against the collection of lines) rather than a substring match. – Charles Duffy Jul 17 '21 at 19:53
  • Thanks; is that really the format produced by `rpm -qa`? No version number etc? I'm not in a place where I have an RPM system to test on. `rpm -q XY` seems to be the way to query the package XY but the manual doesn't reveal exactly what that will print or return, either. – tripleee Jul 18 '21 at 06:48
  • You're right -- I forgot about the version numbers. One can pass rpm a format string to use to force it to exclude that; or it might make more sense to just run `rpm -q packagename` to ask only about the specific package we care about. – Charles Duffy Jul 18 '21 at 12:29