read() or readline() clobbers my variable

Peter Otten __peter__ at web.de
Fri Jul 30 11:15:36 CEST 2004


washu wrote:

> This may be a simple problem but I can't seem to find a way around it.
> I've pasted my code snippet below:
> 
> import os
> 
> input = os.popen("echo hello")
> input.readline()
> input.readline()
> 
> The first input.readline() gives the output.  The second readline() gives
> an empty line.  It almost seems like input acts as a buffer which gets
> emptied when you read it.
> 
> I even tried setting it equal to another variable (temp = input) but it
> seems like temp receives a pointer that just points to input.
> temp.readline() produces the same results.
> 
> I'd like to basically freeze the contents of input for further
> manipulation or comparison.  Any ideas?

In Python 2.4 you have another option in addition to Vincent's suggestion:

>>> import os, itertools
>>> a, b = itertools.tee(os.popen("echo hello"))
>>> a.next()
'hello\n'
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>> b.next()
'hello\n'
>>> b.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

tee() creates two new iterators out of one original (which shouldn't be used
after the tee call). The nice thing about the next() method as opposed to
readline() is that it is called implicitely in a for loop.

>>> a, b = itertools.tee(os.popen("echo hello"))
>>> for i in a: print i
...
hello

>>> for i in b: print i
...
hello

Of course once you have consumed both a and b, the information from the
os.popen() call is lost just like in your readline() example -- unless you
put statements to store at least those lines you are interested in into the
for-loop(s).

Peter




More information about the Python-list mailing list