Read shell output from python line-by-line Read shell output from python line-by-line shell shell

Read shell output from python line-by-line


I'm not really a python guy, but this should work for you and seems a bit clearer:

import subprocesscmd = ["ls", "-la"]proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)for line in proc.stdout.readlines():    print line


Have you tried using join? And use split on newline (\n).

#!/usr/bin/pythonimport subprocessCMD = "ls -la"output = subprocess.check_output(CMD, shell=True)lst = []for char in output:    lst.append(char)print ''.join(lst).split('\n')

Basically join all your output into a single string, and then split on the newline character to create a list of your individual outputs. Also it is bad practice to name a variable list, as this is a type in Python. Try using lst or list1 instead.

You could also simplify it to:

#!/usr/bin/pythonimport subprocessCMD = "ls -la"output = subprocess.check_output(CMD, shell=True)print output.split('\n')

As the return value of subprocess.check_output() is the output as a single string, there is no need to loop through each character, just use split on the string to get the list of outputs.


Both @glenn-jackman and @tui-popenoe answers work:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)for line in proc.stdout.readlines():    print line

and

output = subprocess.check_output(CMD, shell=True)print output.split('\n')

But, I used subprocess.Popen because it was useful for piping:

p1 = subprocess.Popen(['ip','-la'], stdout=subprocess.PIPE)p2 = subprocess.Popen(['grep','afile'], stdin=p1.stdout,stdout=subprocess.PIPE)p3 = subprocess.Popen(['awk','{ print $6; }'], stdin=p2.stdout,stdout=subprocess.PIPE)output = p3.communicate()[0]for ln in output.split('\n'):    print ln