A_D
A_D

Reputation: 705

Issue when using array slicing

I am an intermediate Python programmer. In my experiment, I use Linux command that outputs some results something like this:

OFPST_TABLE reply (xid=0x2):
  table 0 ("classifier"):
    active=1, lookup=41, matched=4
    max_entries=1000000
    matching:
      in_port: exact match or wildcard
      eth_src: exact match or wildcard
      eth_dst: exact match or wildcard
      eth_type: exact match or wildcard
      vlan_vid: exact match or wildcard
      vlan_pcp: exact match or wildcard
      ip_src: exact match or wildcard
      ip_dst: exact match or wildcard
      nw_proto: exact match or wildcard
      nw_tos: exact match or wildcard
      tcp_src: exact match or wildcard
      tcp_dst: exact match or wildcard

My goal is to collect the value of parameter active= which is variable from time to time (In this case it is just 1). I use the following slicing but it does not work:

string = sw.cmd('ovs-ofctl dump-tables ' + sw.name) # trigger the sh command 
count = count + int(string[string.rfind("=") + 1:])

I think I am using slicing wrong here but I tried many ways but I still get nothing. Can someone help me to extract the value of active= parameter from this string?

Thank you very much :)

Upvotes: 1

Views: 57

Answers (2)

Andrey
Andrey

Reputation: 60065

1) Use regular expressions:

import re
m = re.search('active=(\d+)', '    active=1, lookup=41, matched=4')
print m.group(1)

2) str.rfind returns the highest index in the string where substring is found, it will find the rightmost = (of matched=4), that is not what you want.

3) Simple slicing won't help you because you need to know the length of the active value, overall it is not the best tool for this task.

Upvotes: 2

Billy
Billy

Reputation: 5609

How about regex?

import re
count +=  int(re.search(r'active\s*=\s*([^,])\s*,', string).group(1))

Upvotes: 2

Related Questions