stream to string-question

Bengt Richter bokr at oz.net
Mon Jul 1 15:54:39 EDT 2002


On Mon, 1 Jul 2002 18:08:42 +1000, Aldo Cortesi <aldo at nullcube.com> wrote:

>Thus spake Klaus Reinhardt (K.Rdt at TU-Berlin.DE):
>
>> ---------------------------------------------------------------------
>> Hi
>> 	y=os.popen( 'netstat -a -n','r').read()
        y=os.popen( 'netstat -a -n','r').readlines() #(a)
        y=os.popen( 'netstat -a -n','r').read().splitlines() #(b)
>> # Aktive Verbindungen
>> # 
>> #   Proto  Lokale Adresse         Remote-Adresse            Status
>> #   TCP    0.0.0.0:1171           0.0.0.0:0              LISTENING
>> #   TCP    130.149.164.212:1171   130.149.4.11:110       ESTABLISHED
>> 	print y
        ^^^^^^^-- leave out, since this would now be printing ['<1st line>, '<2nd line>', '<etc...>']
>> 	for i in y: 
>> 		print "--------: ", i
                print "--------: ", i.rstrip() #(a) strip trailing whitespace, so print doesn't double it
                print "--------: ", i          #(b) splitlines above does the job
>> The last is outputting each character in a single line. Is
>> there a function to convert this stream in the text-rows?
>
>
>The variable "y" above is a single, long string with some
>embedded newlines. When you iterate over a string you get
>its component characters one by one. 
>
>What you really want to do is to split the string up into a
>list of lines. Luckily, the string type has a method that
>does exactly that... Try:
>	
>	lines = y.splitlines()
>	for l in lines:
>		print "---: ", i
>
I forgot splitlines, so I was going to suggest (a) until I read your suggestion,
which I would then suggest using as in (b).

Regards,
Bengt Richter



More information about the Python-list mailing list