i'am using following regex pull several information file.
def inventory(): open('inventory.log', 'r+') f: match_hostname = re.compile(r'name: "(.+)",') match_pid = re.compile(r'pid: (.+) ,') match_sn = re.compile(r'sn: (.+)') list_text = [text.strip() text in f] line in list_text: match_regex_hostname = match_hostname.search(line) match_regex_pid = match_pid.search(line) match_regex_sn = match_sn.search(line) if match_regex_hostname: final_hostname = match_regex_hostname.group(1).strip(" ") print final_hostname elif match_regex_pid: final_pid = match_regex_pid.group(1).strip(" ") print final_pid elif match_regex_sn: final_sn = match_regex_sn.group(1).strip(" ") print final_sn inventory()
below content of "inventory.log" file.
lab-sw01#show inventory name: "lab-sw01", descr: "my switch" pid: as-2001-xt , vid: n/a, sn: aba0923k0dn
when call function doesn't show result final_sn. tried re-order if statement , revealed works if , first elif statement. miss on code?
if have both pid
, sn
on same line, end running first elif
statement.
try this:
def inventory(): open('inventory.log', 'r+') f: match_hostname = re.compile(r'name: "(.+)",') match_pid = re.compile(r'pid: (.+) ,') match_sn = re.compile(r'sn: (.+)') list_text = [text.strip() text in f] line in list_text: match_regex_hostname = match_hostname.search(line) match_regex_pid = match_pid.search(line) match_regex_sn = match_sn.search(line) if match_regex_hostname: final_hostname = match_regex_hostname.group(1).strip(" ") print final_hostname if match_regex_pid: final_pid = match_regex_pid.group(1).strip(" ") print final_pid if match_regex_sn: final_sn = match_regex_sn.group(1).strip(" ") print final_sn inventory()
Comments
Post a Comment