from collections import defaultdict
import re
def get_computer(row, reg=re.compile('Computer Name: (\S+)')):
m = reg.match(row)
return m and m.group(1)
def line_starts_with(s):
return lambda line: line.startswith(s)
found = line_starts_with('ERROR: The TPM is already on.')
not_found = line_starts_with('ERROR: A compatible Trusted Platform Module (TPM) was not detected.')
def process_states(inf, value_fn, state_fns):
states_matched = defaultdict(list)
value = None
for row in inf:
nv = value_fn(row)
if nv:
value = nv
else:
for state_label,state_fn in state_fns.items():
if state_fn(row):
states_matched[state_label].append(value)
break
return states_matched
def main():
with open('input.log') as inf:
results = process_states(inf, get_computer, {'found':found, 'not_found':not_found})
if __name__=="__main__":
main()
然後進行測試,我皮棉下列內容:
import StringIO
inf = StringIO.StringIO("""
BitLocker Drive Encryption: Configuration Tool version 6.1.7601
Copyright (C) Microsoft Corporation. All rights reserved.
Computer Name: AAAAA
ERROR: A compatible Trusted Platform Module (TPM) was not detected.
---
BitLocker Drive Encryption: Configuration Tool version 6.1.7601
Copyright (C) Microsoft Corporation. All rights reserved.
Computer Name: BBBBBB
ERROR: The TPM is already on.
---
BitLocker Drive Encryption: Configuration Tool version 6.1.7601
Copyright (C) Microsoft Corporation. All rights reserved.
Computer Name: CCCCCC
ERROR: The TPM is already on.
---
BitLocker Drive Encryption: Configuration Tool version 6.1.7601
Copyright (C) Microsoft Corporation. All rights reserved.
Computer Name: DDDDDDD
ERROR: A compatible Trusted Platform Module (TPM) was not detected.
""")
results = process_states(inf, get_computer, {'found':found, 'not_found':not_found})
返回
{'found': ['BBBBBB', 'CCCCCC'], 'not_found': ['AAAAA', 'DDDDDDD']}
做三個連字符表明結束錯誤消息? – 2rs2ts