Python: Nice way to iterate over shell command result

command, exec, python, shell

Solution

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())

Problem

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.

Original source

Related problems