在列表上执行正则表达式以创建新列表

时间:2017-07-10 19:17:05

标签: python regex list

在python中练习一些正则表达式的东西。我想使用python 3解析Linux的一些命令输出。所以下面的代码生成一个按换行符分割的列表。

import subprocess
import re

cmd = 'df -h'
output = subprocess.check_output(cmd, shell=True).decode('utf8')
ln = output.split('\n')
print (ln)

到目前为止一切顺利。现在我想使用正则表达式生成一个新列表来提取一些输出。

在python输出之外运行命令:

Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           787M  9.5M  778M   2% /run
/dev/sda2       211G  9.5G  191G   5% /
tmpfs           3.9G     0  3.9G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/sda1       511M  3.6M  508M   1% /boot/efi
tmpfs           787M   20K  787M   1% /run/user/131
tmpfs           787M   32K  787M   1% /run/user/0

所以说我要提取字符串以/ run /开头的最后一列 使用正则表达式' / run /.*到新列表所以我的代码现在看起来像:

import subprocess
import re


cmd = 'df -h'
output = subprocess.check_output(cmd, shell=True).decode('utf8')
ln = output.split('\n')
r = re.compile('/run.*')
newlist = [filter(r.search, ln)]
print (newlist)

我希望这可以工作(因为我是一个可怕的程序员),但它没有,过滤正确的方法来做到这一点?有人可以提供一些建议吗?

0 个答案:

没有答案