0

I'm running a command where the output is a list of numbers:

output = subprocess.run(['command'], stdout = subprocess.PIPE)

The output (output.stdout.decode('utf-8')) is something like this:

1
534
89
4
57
9

I need to find if a specific number is not in that list. The problem is if I search using if num not in list: for num=3 I will get true since the number 534 is in that list.

How can I check if a number (in a line of its own) is in the list?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Pace
  • 3
  • 1

3 Answers3

0

just split your list and check either for "word" or for integer, using set comprehension to get rid of duplicates:

if 3 in {int(x) for x in output.stdout.decode('utf-8').split()}:

a simpler way is also possible with the direct output of split:

if "3" in output.stdout.decode('utf-8').split():

(less powerful if integers can start with 0: 03)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Just adding to the answer by Jean-Francois . Split() by default splits on white spaces, but since you would be needing to split on lines, I would suggest split('\n') to do the splitting, this way the code would be more resilient

0

You can use re module as well:

import re

lookup=3

pattern = re.compile('\b{}\b'.format(lookup))

if pattern.search(output.stdout.decode('utf-8')):
    ...
zipa
  • 27,316
  • 6
  • 40
  • 58