Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess readlines()?

So I'm trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I'm having is I can't seem to find a way of making readlines() work.

So I used to be able to do

list = os.popen('ls -l').readlines()

But I can't do

list = subprocess.Popen(['ls','-l']).readlines()
like image 424
joedborg Avatar asked Sep 19 '11 09:09

joedborg


2 Answers

ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.stdout.readlines()

or, if you want to read line-by-line (maybe the other process is more intensive than ls):

for ln in ls.stdout:
    # whatever
like image 164
Fred Foo Avatar answered Sep 29 '22 17:09

Fred Foo


With subprocess.Popen, use communicate to read and write data:

out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() 

Then you can always split the string from the processes' stdout with splitlines().

out = out.splitlines()
like image 24
agf Avatar answered Sep 29 '22 18:09

agf