5

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.

Community
  • 1
  • 1
Scheintod
  • 7,953
  • 9
  • 42
  • 61
  • 2
    beware of [block buffering issue](http://stackoverflow.com/q/20503671/4279) and [methods to fix it](http://stackoverflow.com/a/20509641/4279) – jfs Dec 11 '13 at 05:28

2 Answers2

13

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())
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • drop `shell=True`. It is unnecessary here. – jfs Dec 11 '13 at 05:25
  • 2
    @J.F.Sebastian the necessity of `shell=True` depends on the bash scripts the OP is supposed to replace; for commands as simple as `ls ~`, it is necessary to pass `shell=True` – behzad.nouri Dec 11 '13 at 12:55
0

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.

user2926055
  • 1,963
  • 11
  • 10