0

I have a python script that runs through several checks. One of the checks is to make sure the result does not include a keyword by doing a grep on the keyword and confirming there is no output. Reading the grep man page the expected exit code is 1. But from a user perspective the check is passed since the keyword is not present. Is there a way I can return exit status 0 for grep with no match commands so it is not handled as an exception or any other way to ovoid it being handled as an exception? Note users will create the command file so I cannot avoid using grep altogether.

import subprocess


    def cmd_test(command):
        try:
            cmd_output = subprocess.check_output(command,
                                                 stderr=subprocess.STDOUT,
                                                 shell=True,
                                                 timeout=120,
                                                 universal_newlines=False).decode('utf-8')
        except subprocess.CalledProcessError as exc:
            return (exc)
        else:
            return cmd_output.strip()

    print(cmd_test('env | grep bash'))
    print(cmd_test('env | grep test'))

print(cmd_test('env | grep bash'))
print(cmd_test('env | grep test'))

Output:

SHELL=/bin/bash
Command 'env | grep test' returned non-zero exit status 1 b''
MBasith
  • 1,241
  • 2
  • 15
  • 31
  • Err ... just check the exit code in the exception object? Or even just use `Popen` object directly instead of `check_foo()` – o11c Aug 25 '17 at 04:23

1 Answers1

2

Example of grep returning an exit 1 after no match, the normal behaviour:

$ env | grep test
$ echo $?
1

Example of suppressing grep's return value and forcing to 0 exit status:

$ env | { grep test || true; }
$ echo $?
0

Try this. Hope it helps.

Lubos
  • 63
  • 4
  • You could use the `! ` operator like here: https://stackoverflow.com/questions/367069/how-can-i-negate-the-return-value-of-a-process – Arminius Aug 25 '17 at 07:31