Python: Nice way to iterate over shell command result

Viewed 8445

is there a "nice" way to iterate over the output of a shell command?

I'm looking for the python equivalent for something like:

ls | while read file; do
    echo $file
done

Note that 'ls' is only an example for a shell command which will return it's result in multiple lines and of cause 'echo' is just: do something with it.

I known of these alternatives: Calling an external command in Python but I don't know which one to use or if there is a "nicer" solution to this. (In fact "nicer" is the main focus of this question.)

This is for replacing some bash scripts with python.

2 Answers

you can open a pipe ( see doc ):

import os

with os.popen('ls') as pipe:
    for line in pipe:
        print (line.strip())

as in the document this syntax is depreciated and is replaced with more complicated subprocess.Popen

from subprocess import Popen, PIPE
pipe = Popen('ls', shell=True, stdout=PIPE)

for line in pipe.stdout:
    print(line.strip())

check_output will give you back a string you can parse. call will simply re-use your existing stdout/stderr/stdin and simply return the process exit code.

Related