0

我想使用 python for 循环或任何简单的方法httpd_从输出中解析。chkconfig

[spatel@04 ~]$ /sbin/chkconfig --list| grep httpd_
httpd_A    0:off   1:off   2:on    3:on    4:on    5:on    6:off
httpd_B      0:off   1:off   2:off   3:on    4:on    5:on    6:off
httpd_C      0:off   1:off   2:on    3:on    4:on    5:on    6:off

我知道怎么做,bash但我想要同样的东西python

[spatel@04 ~]$ for qw in `/sbin/chkconfig --list| grep httpd_ | awk '{print $1}'`
> do
> echo $qw
> done
httpd_A
httpd_B
httpd_C

如何在python中做到这一点?我的python版本是

[root@04 ~]# python -V
Python 2.4.3
4

1 回答 1

3

使用分割空白行.split()并测试第一个元素是否以字符串开头.startswith()

import subprocess

output = subprocess.check_output(['chkconfig', '--list'])

for line in output.splitlines():
    if line.startswith('httpd_'):
        print line.split()[0]

对于较旧的 python 版本,直接使用Popen()调用:

output = subprocess.Popen(['chkconfig', '--list'], stdout=subprocess.PIPE).stdout

for line in output:
    if line.startswith('httpd_'):
        print line.split()[0]
于 2013-03-06T15:31:04.343 回答