2013-03-06 1 views
0

httpd_chkconfig 출력에서 ​​구문 분석하고 싶습니다. 파이썬을 사용하여 루프를 사용하거나 쉬운 방법을 사용하십시오. 파이썬은 파일을 구문 분석하고 루프에 넣습니다.

[[email protected] ~]$ /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에서 같은 일을합니다.

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

파이썬으로 어떻게 할 수 있습니까?

import subprocess 

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

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

오래된 파이썬 버전의 경우, 직접 Popen() 전화를 사용합니다 : 첫 번째 요소는 문자열 .startswith()을 사용하여 시작하면 내 파이썬 버전은

[[email protected] ~]# python -V 
Python 2.4.3 
+1

외 : bash는 다소 복잡합니다. 시도해보십시오 :'/ sbin/chkconfig --list | awk '/^httpd_/{print $ 1}''. 'for'와'grep'과 backticks는 필요 없습니다. –

+0

그건 문제가 아니에요, 파이썬에서 같은 기능을 원합니다 ... – Satish

+1

맞습니다 - 그 이유는 주석 이요 대답이 아닙니다. –

답변

3

분할 .split() 및 테스트를 사용하여 공백에 라인

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

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

AttributeError : 'module'객체에 'check_output'속성이 없습니다. – Satish

+0

내 버전은 Python 2.4.3 (# 1, 2011 5 월 5 일, 16:39:10) – Satish

+1

입니다. @Satish : 아, 오래된 Python 버전입니다. –

관련 문제