python从文件内容为“Total PSS by process:”的下一行开始读取文件
时间: 2024-03-06 22:49:28 浏览: 14
可以使用Python中的文件操作来实现从文件内容为“Total PSS by process:”的下一行开始读取文件。具体实现可以使用以下代码:
```python
with open('filename.txt') as f:
for line in f:
if line.strip() == 'Total PSS by process:':
break
for line in f:
# 从第二行开始读取文件内容
print(line)
```
在这段代码中,首先使用`with open('filename.txt') as f:`语句打开文件,并使用`for line in f:`循环逐行读取文件内容。当读取到文件内容为“Total PSS by process:”的一行时,使用`break`语句跳出循环,然后再次使用`for line in f:`循环读取文件内容,此时从第二行开始读取文件内容。
相关问题
TOTAL PSS: 24492 TOTAL RSS: 87324 TOTAL SWAP PSS: 4063 中我只想要TOTAL PSS
你可以在 `excecmd` 函数中修改命令字符串,只保留 `TOTAL PSS` 部分的输出,可以这样修改:
```python
if 'Windows' in platform.system():
cmd = "adb shell dumpsys meminfo %s |findstr \"TOTAL PSS:\""
else:
cmd = "adb shell dumpsys meminfo %s |grep \"TOTAL PSS:\""
```
这样,`excecmd` 函数只会返回 `TOTAL PSS:` 部分的输出,而不包括 `TOTAL RSS:` 和 `TOTAL SWAP PSS:`。然后在 `get_mem` 函数中,将提取出来的 `pss1` 转换为整数即可:
```python
for proc in procs:
pss1 = int(excecmd(cmd % proc)[1].split()[2])
pss.append(pss1)
pss = max_avg(pss)[2]
result["pss"] = pss
```
这样就可以只返回 `TOTAL PSS` 的值了。
TOTAL PSS: 24492 TOTAL RSS: 87324 TOTAL SWAP PSS: 4063 转换成字典
可以将这些数据转换为一个Python字典,格式如下:
```
{
"TOTAL PSS": 24492,
"TOTAL RSS": 87324,
"TOTAL SWAP PSS": 4063
}
```
您可以使用以下代码将其转换:
```python
data = "TOTAL PSS: 24492 TOTAL RSS: 87324 TOTAL SWAP PSS: 4063"
stats = {}
for stat in data.split():
key, value = stat.split(":")
stats[key] = int(value)
print(stats)
```