Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A more concise way to write this Python code

Tags:

python

In Python, I'd like to test for the existence of a keyword in the output of a Linux command. The keywords to test for would be passed as a list as shown below. I've not spent a lot of time with Python so brute-force approach is below. Is there a cleaner way to write this?

def test_result (result, mykeys):

  hit = 0
  for keyword in mykeys:
     if keyword in result:
        hit = 1
        print "found a match for " + keyword

  if hit == 1:
     return True


result = "grep says awk"
mykeys = ['sed', 'foo', 'awk']
result = test_result (result, mykeys)
like image 648
Koko Avatar asked Jan 27 '26 19:01

Koko


1 Answers

The any built-in will do it.

def test_result(result, mykeys):
    return any(key in result for key in mykeys)
like image 54
hdiogenes Avatar answered Jan 30 '26 10:01

hdiogenes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!