2016-12-13 2 views
1

나는 중급 Python 프로그래머입니다. 내 실험에서, 나는이 같은 일부 결과 뭔가를 출력 리눅스 명령을 사용합니다배열 슬라이스 사용시의 문제

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 

내 목표는 때때로 변수 매개 변수 active=의 값을 수집하는 것입니다 (이 경우는 1). 나는 다음과 같은 슬라이스를 사용하지만 그것은 작동하지 않습니다

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

내가 잘못 여기에 슬라이스하지만 난 많은 방법을 시도하지만 난 아직 아무것도 얻을 사용하고 생각합니다. 누군가가이 문자열에서 active= 매개 변수의 값을 추출하는 데 도움을 줄 수 있습니까?

은 대단히 감사합니다 :)

답변

2

어떻게 regex 대해를?

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

정말 고마워요. 매우 깔끔하게 .. .. –

2

1) 정규 표현식을 사용

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

2) str.rfind 반환 문자열이 발견되는 문자열에서 가장 높은 인덱스를, 그것은, 즉) 맨 오른쪽 = (matched=4의를 찾을 수 네가 원하는게 아니야.

3) 단순 슬라이스는 활성 값의 길이를 알아야하기 때문에 도움이되지 않습니다. 전반적으로이 작업에 가장 적합한 도구는 아닙니다.

+0

해명 해 주셔서 감사합니다. –