0

I want to parse httpd_ from chkconfig output using python for loop or whatever the easy way.

[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

I know how to do in bash but i want same thing in python.

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

How to do it in python? my python version is

[root@04 ~]# python -V
Python 2.4.3
4
  • 1
    Aside: your bash is somewhat convoluted. Try: /sbin/chkconfig --list | awk '/^httpd_/ { print $1 }'. for and grep and backticks are not required. Commented Mar 6, 2013 at 15:36
  • That is not an issue, i want same function in python... Commented Mar 6, 2013 at 15:38
  • 1
    Right -- that's why its a comment and not an answer. Commented Mar 6, 2013 at 15:38
  • @Robᵩ that is so sweet. good to know we can use awk for extract string.. upvote for it. Commented Mar 6, 2013 at 15:46

1 Answer 1

3

Split the line on whitespace using .split() and test if the first element starts with a string using .startswith():

import subprocess

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

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

For older python versions, use a Popen() call directly:

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

for line in output:
    if line.startswith('httpd_'):
        print line.split()[0]
Sign up to request clarification or add additional context in comments.

6 Comments

AttributeError: 'module' object has no attribute 'check_output'
My version is Python 2.4.3 (#1, May 5 2011, 16:39:10)
@Satish: ah, old, old python version then.
All latest Linux machines are having Python2.6 which does not have attribute check_output. AttributeError: 'module' object has no attribute 'check_output'.
@kvivek: that returns the exit code, useless if you want to read it's stdout instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.