['BMC current time:2026-02-19 15:36:32', '===commond:free BEGIN===', 'mem total:358', 'mem used:296', 'mem free:62', '===commond:free END===', 'bmccurrenttime:2026-02-19 15:36:32', '---test---:912_ /usr/local/bin/execdaemon---BRGIN--', 'sysadmin 912 1 0 Feb11 ? 00:03:43 /usr/local/bin/execdaemon', '===proc===912_ /usr/local/bin/execdaemon===smaps===BEGIN===', '00012000-00033000 rw-p 00000000 00:00 0 [heap]', 'Size: 132 kB', 'Rss: 4 kB', 'Pss: 4 kB', 'Shared_Clean: 0 kB', 'Shared_Dirty: 0 kB', 'Private_Clean: 0 kB', 'Private_Dirty: 4 kB', 'Referenced: 4 kB', 'Anonymous: 4 kB', 'AnonHugePages: 0 kB', 'Swap: 0 kB', 'KernelPageSize: 4 kB', 'MMUPageSize: 4 kB', 'Locked: 0 kB', 'VmFlags: rd wr mr mw ] 正则匹配找出free BEGIN ,提出mem total:358 mem used:296 mem free:62 返回{'memSize':{'total':358,'used':296,'free':62}}格式
时间: 2024-04-22 09:27:58 浏览: 134
你可以使用Python的正则表达式模块re来匹配和提取需要的信息。下面是一个示例代码,用于匹配"free BEGIN"行之后的"mem total"、"mem used"和"mem free"的值,并将其存储在一个字典中:
```python
import re
content = [
'BMC current time:2026-02-19 15:36:32',
'===commond:free BEGIN===',
'mem total:358',
'mem used:296',
'mem free:62',
'===commond:free END===',
'bmccurrenttime:2026-02-19 15:36:32',
'---test---:912_ /usr/local/bin/execdaemon---BRGIN--',
'sysadmin 912 1 0 Feb11 ? 00:03:43 /usr/local/bin/execdaemon',
'===proc===912_ /usr/local/bin/execdaemon===smaps===BEGIN===',
'00012000-00033000 rw-p 00000000 00:00 0 [heap]',
'Size: 132 kB',
'Rss: 4 kB',
'Pss: 4 kB',
'Shared_Clean: 0 kB',
'Shared_Dirty: 0 kB',
'Private_Clean: 0 kB',
'Private_Dirty: 4 kB',
'Referenced: 4 kB',
'Anonymous: 4 kB',
'AnonHugePages: 0 kB',
'Swap: 0 kB',
'KernelPageSize: 4 kB',
'MMUPageSize: 4 kB',
'Locked: 0 kB',
'VmFlags: rd wr mr mw ]'
]
# 使用正则表达式匹配"free BEGIN"行之后的"mem total"、"mem used"和"mem free"的值
pattern = r'mem total:(\d+)\nmem used:(\d+)\nmem free:(\d+)'
match = re.search(pattern, '\n'.join(content))
if match:
total = int(match.group(1))
used = int(match.group(2))
free = int(match.group(3))
# 构建字典
result = {
'memSize': {
'total': total,
'used': used,
'free': free
}
}
print(result)
else:
print("无法找到匹配的内容")
```
在上面的示例中,我们使用正则表达式模式`r'mem total:(\d+)\nmem used:(\d+)\nmem free:(\d+)'`来匹配"free BEGIN"行之后的"mem total"、"mem used"和"mem free"的值。然后使用`re.search()`函数从字符串中找到第一个匹配项,并使用`match.group()`方法提取匹配到的各个值。最后,将提取到的值存储在一个字典中,并按照指定的格式输出。
以上示例将输出:
```
{'memSize': {'total': 358, 'used': 296, 'free': 62}}
```
请注意,根据实际情况,你可能需要根据文件内容的变化对正则表达式进行适当的修改。
阅读全文