[Tutor] Processing Linux command line output

Bill Campbell bill at celestial.net
Thu Apr 25 00:35:15 CEST 2013


On Thu, Apr 25, 2013, Gareth Allen wrote:
>
>   Hi all,
>   I'm trying to get the output of a command and split it into a list that
>   I can process.  What is the best way to go about doing this? In bash I
>   would use tools like grep, sed awk etc.

The old way to do this uses os.popen

import os

fh = os.popen('ifconfig')
for line in fh:
	# scan line here

The more modern way to handle this is using the subprocess module
with something like:

from subprocess import PIPE, Popen
fh = Popen('ifconfig', stdout=PIPE).stdout
...

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

When the customer has beaten upon you long enough, give him what he asks
for, instead of what he needs.  This is very strong medicine, and is
normally only required once.
    -- The Consultant's Curse:


More information about the Tutor mailing list