1

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 :)

2 Answers 2

2

How about regex?

import re
count +=  int(re.search(r'active\s*=\s*([^,])\s*,', string).group(1))
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thank you for clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.