[Tutor] Fwd: print a for loop system call
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Jan 20 18:39:56 EST 2018
On 20/01/18 18:26, Derek Smith wrote:
> import os
> import sys
> from subprocess import Popen, PIPE
>
> pipe = Popen('lsdev -c tape', shell=True, stdout=PIPE)
>
> for dev in pipe.stdout :
> print ( dev.strip().split()[0].decode() ) ## A ##
This is OK
> # print ( dev.strip().split().decode()[0] ) ## B ##
This tries to decode a list which won't work.
split() returns a list.
You want to apply decode to a string,
specifically the first string that split produces,
so it is correct as in option A.
If in doubt split the line up and print each
component as you create it:
for dev in pipe.stdout :
print( dev.strip() )
print( dev.strip().split())
print( devb.strip().split()[0])
print( dev.strip().split()[0].decode() )
> And if I try to store in an array using
>
> rmts = [ dev.strip().split()[0].decode() ]
>
> it only stores the last line when there are over 100 lines.
Wrong, it stores every line as it comes to it.
But, since you create a new list each time you
throw way the previous one. Only the last list
is preserved, but they were all stored, albeit
briefly...
You need to append() to a list, something like:
aList = []
for dev in....
process dev
aList.append(result)
Or as a list comprehension:
aList = [process(dev) for dev in ....]
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list